Your privacy matters: This site uses cookies to analyze site usage and provide social media features. Learn More.

What’s New in Angular 6 – Part 1

May 12, 2018 in JavaScript Articles

Written by John Paxton


Angular 6 has been released by the Angular development team at Google. There are several changes in this major version update. With these revisions, Angular is more stable and organizes its infrastructure much better. The CLI, Angular Material, and a host of features have been improved, and most developers will want to take advantage of these enhancements.

Here are the big changes in Angular 6:

  • Update to TypeScript version 2.7
  • Update to RxJS version 6
  • Forms improvements
  • Routing improvements
  • CLI and Material versions harmonized with the rest of Angular
  • Updates and additions to CLI features
  • Updates to Material features
  • Elements: Self-contained Angular components!

We will cover these adjustments across a series of articles. In this first article, I will cover library updates, changes to the core parts of Angular, and improvements to Forms.

Library Updates in Angular 6

TypeScript has now been updated to version 2.7. You can see the changes for TypeScript 2.7 here https://github.com/Microsoft/TypeScript/wiki/What’s-new-in-TypeScript#typescript-27.

RxJS, the package that provides Observables (which are used throughout Angular), has been updated to version 6.0.0.

Visit https://github.com/ReactiveX/rxjsfor the repo.

The changelog is here: ttps://github.com/ReactiveX/rxjs/blob/master/CHANGELOG.md.

It would also be helpful to look at the migration guide: https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md.

Angular 4 marked the <template> tag as deprecated, and Angular 6 removes it and replaces it with the use of <ng-template> which works the same and will not interfere with future HTML tags called “template”.

While this would work in Angular 5…

<p *ngIf="count > 5; else equalToFiveTemplate">Count is greater than 5.</p>
<template #equalToFiveTemplate> 
  <p>Count is equal to 5.</p>
</template>

This is how you would do it in Angular 6:

<p *ngIf="count > 5; else equalToFive">Count is greater than 5.</p>
<ng-template #equalToFiveNgTemplate> 
  <p>Count is equal to 5.</p>
</ng-template>

Angular 6 Forms

There have been several refinements to the way forms work. Almost all of them relate to the mechanics of validation: getting status updates, fixing bugs, and adding validation capabilities. Also, ngModelChange’s API was clarified (or, from another perspective, had a bug fixed!).

  • markAsPending event
  • ngModelChange feature/bugfix
  • pattern validators
  • Multiple validators in Reactive Forms Form Arrays

When Angular 2 was released, it included a new API for what it called Reactive Forms, which is sort of an inversion of control pattern for form design. Standard templated forms are oriented towards the HTML side of the component “pushing” data to the component class. Reactive forms are designed in the component class and attached to the template as needed. The Angular docs have a discussion of reactive forms here (https://angular.io/guide/reactive-forms).

In Angular 6, the markAsPending method defined in AbstractControl and inherited in FormControl, FormGroup, and FormArray, now emits a PENDING event. This ties into the validation state of a control, which can be VALID, INVALID, or PENDING. Recall that controls can be validated asynchronously, which is why the PENDING status existed in the first place. Now that PENDING also emits an event, we can write code which reacts to a validation that is in-progress.

import{Component,OnInit }from'@angular/core';
import{AbstractControl,FormControl,FormGroup }from'@angular/forms';

@Component({
  selector :'mark-as-pending',
  templateUrl :'mark-as-pending.component.html',
  styles :[]
})
exportclassMarkAsPendingComponent implementsOnInit {

  personForm =newFormGroup({
    firstName:newFormControl('',[],[this.asyncValidator()])
  });
  firstName:FormControl;
  controlStatus:string;

  ngOnInit(){

    // The PENDING event is captured here
    this.personForm
      .get('firstName')
      .statusChanges
      .forEach((value:string)=>this.controlStatus =value );
  }

  asyncValidator(){
    // control.markAsPending() is implicitly called here
    // because this is an async validator;

    return(control:AbstractControl )=>{
      console.log('Validating firstName...',control );
      returnnewPromise(resolve =>setTimeout(resolve,2000));
    };
  }
}

The ngModelChange event had a subtle issue (not even necessarily a bug). If you accessed the changed value of a form field via the magic $event variable, you received the data you expected. That is, any time there was a change, you saw the updated and changed value of the form field. However, if you tried to access the value of the form field via the ngModel instance (using a template variable), you would get the value of the form field BEFORE it updated.

This has been fixed in Angular 6.

You can see an example of the old behavior – https://stackblitz.com/github/speedingplanet/ngmodelchange-old

The improved behavior is here: https://stackblitz.com/github/speedingplanet/ngmodelchange-six

Given this HTML:

<div>
  <label for="model-text">At ngModel time</label>
  <input type="text"
  id="model-text"
  name="model-text"
  #modelHook="ngModel"
  [(ngModel)]="modelText"
  (ngModelChange)="handleModel(<em>modelHook</em>)"
  (blur)="modelText=''">
</div>
<div>
  <p>Data at handler time: <span [class.highlight]= "modelText&& handlerText!==   modelText">{{ handlerText  }}</span></p>
  <p>Data at ngModel time: <span>{{ modelText   }}</span></p>
</div>

Note that the input field has a templateVariable #modelHook as well as an ngModel value of modelText.

Now, the backing component:

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styles: ['.highlight {background-color: yellow}']
})
export class AppComponent {

  @Input()
  modelText: string;

  handlerText: string;

  handleModel(model: NgModel) {
    <em>console</em>.log('Model: ', model);
    this.handlerText = model.value;
  }
}

Under Angular 5, the value printed as handlerText would consistently be behind the value in modelText by one letter. This was due to ngModel (and event) values updating later than model values.

Two other improvements to forms debuted with Angular 6.

  1. Pattern validators now accept line boundaries. In regular expression pattern matching, you can use a ^ (caret) character to catch the beginning of a line and a $ character to catch the end of the line.Before Angular 6, these boundaries were implicitly added to any pattern validator. This meant that if you added them explicitly, the result was an error.In Angular 6, you can add the line boundaries explicitly without errors (and take advantage of them in places like textareas or multi-line text widgets).<input type [name]=”firstname” pattern=”^[A-Z][a-z]+”>
  1. Angular 6 also updates Reactive Forms. Previously, if you used FormBuilder and FormArray, you could only add one validator via FormBuilder.array. Now, you can add as many validators as you would like.

The changes noted in this article are most of the changes to the core part of Angular. In another week or so, we will publish an article on the changes to the Angular command line interface. See you then!

For more Angular 6 examples, please visit https://stackblitz.com/github/speedingplanet/ng-six-demos

Continue Reading


Author: John Paxton, one of Accelebrate’s instructors.

Accelebrate offers private Angular training for groups and instructor-led online Angular classes for individuals.  Visit /angular-training to see the full list of courses.


Written by John Paxton

John Paxton

John is a trainer, programmer and consultant with more than twenty years of experience in JavaScript, Java, SQL, web applications, and other technologies. He has written several courses and one book and has taught on six continents.



Contact Us:

Accelebrate’s training classes are available for private groups of 3 or more people at your site or online anywhere worldwide.

Don't settle for a "one size fits all" public class! Have Accelebrate deliver exactly the training you want, privately at your site or online, for less than the cost of a public class.

For pricing and to learn more, please contact us.

Contact Us Train For Us

Toll-free in US/Canada:
877 849 1850
International:
+1 678 648 3113

Toll-free in US/Canada:
866 566 1228
International:
+1 404 420 2491

925B Peachtree Street, NE
PMB 378
Atlanta, GA 30309-3918
USA

Subscribe to our Newsletter:

Never miss the latest news and information from Accelebrate:

Microsoft Gold Partner

Please see our complete list of
Microsoft Official Courses

Recent Training Locations

Alabama

Huntsville

Montgomery

Birmingham

Alaska

Anchorage

Arizona

Phoenix

Tucson

Arkansas

Fayetteville

Little Rock

California

San Francisco

Oakland

San Jose

Orange County

Los Angeles

Sacramento

San Diego

Colorado

Denver

Boulder

Colorado Springs

Connecticut

Hartford

DC

Washington

Florida

Fort Lauderdale

Miami

Jacksonville

Orlando

Saint Petersburg

Tampa

Georgia

Atlanta

Augusta

Savannah

Idaho

Boise

Illinois

Chicago

Indiana

Indianapolis

Iowa

Ceder Rapids

Des Moines

Kansas

Wichita

Kentucky

Lexington

Louisville

Louisiana

Banton Rouge

New Orleans

Maine

Portland

Maryland

Annapolis

Baltimore

Hagerstown

Frederick

Massachusetts

Springfield

Boston

Cambridge

Michigan

Ann Arbor

Detroit

Grand Rapids

Minnesota

Saint Paul

Minneapolis

Mississippi

Jackson

Missouri

Kansas City

St. Louis

Nebraska

Lincoln

Omaha

Nevada

Reno

Las Vegas

New Jersey

Princeton

New Mexico

Albuquerque

New York

Buffalo

Albany

White Plains

New York City

North Carolina

Charlotte

Durham

Raleigh

Ohio

Canton

Akron

Cincinnati

Cleveland

Columbus

Dayton

Oklahoma

Tulsa

Oklahoma City

Oregon

Portland

Pennsylvania

Pittsburgh

Philadelphia

Rhode Island

Providence

South Carolina

Columbia

Charleston

Spartanburg

Greenville

Tennessee

Memphis

Nashville

Knoxville

Texas

Dallas

El Paso

Houston

San Antonio

Austin

Utah

Salt Lake City

Virginia

Richmond

Alexandria

Arlington

Washington

Tacoma

Seattle

West Virginia

Charleston

Wisconsin

Madison

Milwaukee

Alberta

Edmonton

Calgary

British Columbia

Vancouver

Nova Scotia

Halifax

Ontario

Ottawa

Toronto

Quebec

Montreal

Puerto Rico

San Juan

© 2013-2019 Accelebrate, Inc. All Rights Reserved. All trademarks are owned by their respective owners.