首页 > 解决方案 > 如何检查 ngModel 输入字段是否脏?

问题描述

我有这个 HTML 模板:

<input type="text"
  ngModel
  #myValue="ngModel"
  name="{{ fieldName }}"
  id="{{ fieldName }}"
  value="{{ myVal }}"
  class="form-control"
  (change)="checkDirty(myValue)">

如何检查 my.component.ts 文件中的此字段是否脏?

现在我在 my.component.ts 文件中只有这个基本代码:

export class UriFieldComponent implements OnInit {
    constructor() { }

    ngOnInit() { }

    checkDirty(value) {
        // in here I need to check is dirty or not
    }
}

标签: angularangular7dirty-checking

解决方案


NgModel 类中有一个属性。这意味着您可以执行以下操作:

checkDirty(value) {
    if (value.dirty) {
      ...
    }
}

但是,您使用它的方式不正确,如果您检查输入更改时的脏属性,很明显输入是脏的!换句话说,如果你要使用你的checkDirty函数,输入总是很脏的。


推荐阅读