[英]How do I programmatically set an Angular 2 form control value?
How do I change an Angular 2 control from code? 如何从代码中更改Angular 2控件?
When I do it like this: 当我这样做时:
control.value = "new value";
I get the following error: 我收到以下错误:
TypeError: Cannot set property value of #<AbstractControl> which has only a getter
You can use the updateValue
method: 您可以使用
updateValue
方法:
control.updateValue("new value");
update: 更新:
You can now use setValue
: 您现在可以使用
setValue
:
control.setValue("new value");
在访问updateValue
方法之前,您需要将AbstractControl
转换为Control
:
(<Control>yourControl).updateValue(val);
You need to use both updateValue
and updateValueAndValidity
to update the value of a control and also trigger validators / calculate state. 您需要同时使用
updateValue
和updateValueAndValidity
来更新控件的值,并触发验证器/计算状态。
Here is a sample: 这是一个示例:
control.updateValue("new value");
control.updateValueAndValidity();
In the final version of Angular 2, the .changeValue(newValue: string)
method was removed and exchanged for .patchValue(newValue: string)
在Angular 2的最终版本中,
.changeValue(newValue: string)
方法被删除并交换.patchValue(newValue: string)
so you can do control.patchValue('your new value goes here');
所以你可以做
control.patchValue('your new value goes here');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.