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
4 Answers
Reset to default 12You 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');