Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the ng change in angular 2 using ng model variable

Tags:

angular

How can I use the ng-change event in angular 2? Whenever the ng-model variable is changed, a function has to be called.

[(ngModel)]="variable" ngchange=variable; 
like image 360
Arron Avatar asked Apr 26 '16 14:04

Arron


People also ask

What is NG model and Ng change?

Ng-change is a directive in AngularJS which is meant for performing operations when a component value or event is changed. In other words, ng-change directive tells AngularJS what to do when the value of an HTML element changes. An ng-model directive is required by the ng-change directive.

How do I change the value of ngModel?

If we use two way binding syntax for ngModel the value will be updated. So the default (ngModelChange) function will update the value of ngModel property. i.e., user.Name . And the second (ngModelChange) will be triggered printing the user name value in the console.

What is [( ngModel )]?

Angular NgModel is an inbuilt directive that creates a FormControl instance from the domain model and binds it to a form control element. The ngmodel directive binds the value of HTML controls (input, select, textarea) to application data. We can merely achieve it in the component element and the HTML element both.


1 Answers

You could use the ngModelChange event:

[(ngModel)]="variable" (ngModelChange)="doSomething($event)" 

Edit

According to your comment, I think that you should use form control with a custom validator.

Here is a sample:

@Component({   (...)   template: `     <input [(ngModel)]="variable" [ngFormControl]="ctrl"/>   ` }) export class SomeComponent {   constructor() {     this.ctrl = new Control('', (control) => {       // validate the value     });      this.ctrl.valueChanges.subscribe((value) => {       // called when the value is updated     });    } } 

See this article for more details:

  • http://restlet.com/blog/2016/02/11/implementing-angular2-forms-beyond-basics-part-1/
like image 110
Thierry Templier Avatar answered Sep 30 '22 20:09

Thierry Templier