简体   繁体   English

如何以编程方式设置Angular 2表单控件值?

[英]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. 您需要同时使用updateValueupdateValueAndValidity来更新控件的值,并触发验证器/计算状态。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM