【问题标题】:using the ng change in angular 2 using ng model variable使用 ng 模型变量在角度 2 中的 ng 变化
【发布时间】:2016-04-26 14:10:10
【问题描述】:

如何在 Angular 2 中使用 ng-change 事件?每当更改 ng-model 变量时,都必须调用一个函数。

[(ngModel)]="variable"
ngchange=variable;

【问题讨论】:

  • 每当变量的值改变时,我必须调用函数来验证变量\

标签: angular


【解决方案1】:

您可以使用ngModelChange 事件:

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

编辑

根据您的评论,我认为您应该将表单控件与自定义验证器一起使用。

这是一个示例:

@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
    });

  }
}

查看这篇文章了解更多详情:

【讨论】:

    【解决方案2】:

    组件有双向绑定

    • () 用于输出
    • [] 输入

    这意味着您可以使用 ==>[value]="variable"(input)="setVariable($event)"

    event.target.value

    仅供参考==>https://angular.io/docs/ts/latest/guide/user-input.html

    【讨论】:

    • 你也可以使用模板变量代替$event
    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多