【发布时间】: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