Eran Shabi
Eran Shabi

Reputation: 15019

How do I programmatically set an Angular 2 form control value?

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

Upvotes: 9

Views: 11353

Answers (4)

Eran Shabi
Eran Shabi

Reputation: 15019

You can use the updateValue method:

control.updateValue("new value");

update:

You can now use setValue:

control.setValue("new value");

Upvotes: 12

Pstr
Pstr

Reputation: 857

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');

Upvotes: 1

Des Horsley
Des Horsley

Reputation: 1888

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

(<Control>yourControl).updateValue(val);

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202306

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();

Upvotes: 1

Related Questions