Angular2:有没有办法通过访问$ event来将输入设置为pristine?

时间:2017-06-08 17:58:11

标签: angular

我有一张可以访问其控制器的表单。我可以在它上面运行markAsPristine方法。

我可以执行this.form.controls.password.markAsPristine();,所有这些都适合我。

事实是,当我通过$ event接收他时,我想直接标记AsPristine输入。意思是这样的:

<input 
  [formControl]="password" 
  type="password" class="form-control 
  (input)="checkIfPasswordIsEmpty($event)">

checkIfPasswordIsEmpty(event): void {
    if (event.currentTarget.value === '') {
      this.form.controls.password.markAsPristine();
    }
  }

现在,正如你们所看到的那样,我通过直接在控件对象中访问它来将输入标记为原始。我希望避免专门调用它,并通过方法$event收到的checkIfPasswordIsEmpty($event)访问它。

是否存在这种选择? 谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用control指令来实现此目的。这是我如何做Angular 4,我相信在2中类似。
在模板中:     #password口令=&#34; ngModel&#34;
在组件中:     export class SomeComponent { @ViewChild('password') password: NgModel;
在使原始的功能:      this.password.reset()

答案 1 :(得分:0)

我猜你想在更多的输入和内部使用checkIfPasswordIsEmpty()检查哪一个输入触发了它。我会像下面那样实现它:

<强> HTML

 <input id="password"
    formControlName="password" #password
    type="password" class="form-control" 
    (input)="checkIfPasswordIsEmpty($event)">

<强>打字稿

   checkIfPasswordIsEmpty(event): void {
      let field = (event.srcElement.attributes[2].value); // get which input fired this method
      let value = this.user.get(field).value; // get its value
      if (!value) {
          this.user.get(field).markAsPristine(); //set it pristine
      }
   }

<强> DEMO