【问题标题】:Change input value using NgModel object reference. Angular 5使用 NgModel 对象引用更改输入值。角 5
【发布时间】:2019-07-19 13:23:16
【问题描述】:

我有一个实现了模板驱动验证的 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
}

但是,这不起作用,因为它不是正确的方法。请帮忙!

【问题讨论】:

  • un 应该是FormControl,你应该试试this.un.setValue("xyz")
  • 什么时候你需要重置这个值。为什么你需要访问 NgModel 或 DOM 元素才能做到这一点?您正在使用双向绑定,所以只需执行this.loginDetail.username = ''
  • @BillCheng 我做了this.un.control.setValue(null) 并且成功了。谢谢!!!
  • @JBNizet 我完全同意,但我有一种情况我不能这样做。抱歉,无法解释原因。

标签: angular


【解决方案1】:

试试

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

【讨论】:

  • nativeElement 可用于模板引用变量。但是,this.un 是 NgModel 对象参考
猜你喜欢
  • 1970-01-01
  • 2021-09-25
  • 2018-10-12
  • 2016-10-02
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 2018-04-06
  • 2021-09-12
相关资源
最近更新 更多