using the ng change in angular 2 using ng model variable

前端 未结 2 1923
不思量自难忘°
不思量自难忘° 2021-02-03 18:05

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=variab         


        
相关标签:
2条回答
  • 2021-02-03 18:59

    component have two-way binding

    • () for output
    • [] for input

    that means you can use ==>[value]="variable"<== for showing data on html and ==>(input)="setVariable($event)"<== to update your var in ts/js.

    event.target.value

    FYI==>https://angular.io/docs/ts/latest/guide/user-input.html

    0 讨论(0)
  • 2021-02-03 19:00

    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/
    0 讨论(0)
提交回复
热议问题