Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 957
Eran Shabi Avatar asked Jun 15 '16 20:06

Eran Shabi


People also ask

How do you make a form control dirty?

You should use the markAsDirty method, like this: control. markAsDirty(); This will also mark all direct ancestors as dirty to maintain the model.

How do I use updateValueAndValidity?

You can subscribe to value changes of a control or the whole form. updateValueAndValidity allows you to modify the value of one or more form controls and the flag allows you to specify if you want this to emit the value to valueChanges subscribers.


2 Answers

You can use the updateValue method:

control.updateValue("new value");

update:

You can now use setValue:

control.setValue("new value");
like image 190
Eran Shabi Avatar answered Oct 05 '22 04:10

Eran Shabi


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

(<Control>yourControl).updateValue(val);
like image 23
Des Horsley Avatar answered Oct 05 '22 02:10

Des Horsley