最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I programmatically set an Angular 2 form control value? - Stack Overflow

programmeradmin5浏览0评论

How do I change an Angular 2 control from code?

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

How do I change an Angular 2 control from code?

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
Share Improve this question asked Jun 15, 2016 at 20:22 Eran ShabiEran Shabi 15k8 gold badges33 silver badges51 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

You can use the updateValue method:

control.updateValue("new value");

update:

You can now use setValue:

control.setValue("new value");

You'll need to cast the AbstractControl to a Control before you have access to the updateValue method:

(<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.

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)

so you can do control.patchValue('your new value goes here');

发布评论

评论列表(0)

  1. 暂无评论