使用 NgModel 对象引用更改输入值.角度 5.



我有一个实现了模板驱动验证的 Angular 表单。

例如:

<input name="username" #username="ngModel" [(ngModel)]="loginDetail.username">

现在,我需要使用 ViewChild 访问组件中的该输入字段。

元件

@ViewChild('username') un;
ngOnInit() {
  console.warn(this.un.value);
}

现在,这将打印输入的值(如果有(。但是,我需要,如果存在任何特定值,我需要重置输入值。例如:

ngOnInit() {
  if(this.un.value == "username") {
    // Reset the input value to null
  }
}

但是,我不知道该怎么做。

我试过了:

if(this.un.value == "username") {
  this.un.value = null;    // <-- This does nothing
}

但是,这是行不通的,因为它不是正确的方法。请帮忙!

试试

if(this.un.value == "username") {
  this.un.nativeElement.value = null;
}

最新更新