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;
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With