US & Canada: 877 849 1850
International: +1 678 648 3113

Accelebrate Blog

ACCELERATED LEARNING, CELEBRATED RESULTS

What’s New in Angular 6 – Part 1

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 https://www.accelebrate.com/angular-training to see the full list of courses.

Categories: JavaScript Articles
Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Your email address will not be published. Required fields are marked *

*



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Please contact us for GSA pricing.
Contract #GS-35F-0307T

Please see our complete list of
Microsoft Official Courses