Angular – Reactive Forms – Change

Angular Reactive Forms can manage changes from the user via events in the code. This can enable us to change validation rules, display messages, change user interface elements or much more..

Here’s an example of adding a notification based on a value change. This one is setup from within OnInit:

this.customerForm.get('note').valueChanges.subscribe(value => this.setNotify(value));

We can move validation messaging from the html into the component code allowing us a lot more flexibility.

const myControl = this.customerForm.get('group.myControl');
myControl.valueChanges.subscribe(value => {
   this.setMessage(myControl);
});

setMessage(c: AbstractControl) : void {
   this.message = '';
   if((c.touched || c.dirty) && c.errors) {
      this.message = Object.keys(c.erros).map(key =>
         this.validation<essages[key]).join(' '); 
   }
}
});

HTML:


   {{message}}


Leave a Reply

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