Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 update form control value

I have a problem building dynamic angular2 forms with controls and select boxes, for example this plunker:

    <select class="form-control" ngControl="power">       <option *ngFor="#p of powers" [value]="p">{{p}}</option>     </select> 

You can select a hero power, and the control will have the same value. But if you press Change Powers, the selected value would be null but the control value is still the old value. This is a serious problem I think as this is a source of a lot of bugs when the form shows one thing but in reality it will submit something different, is there some way to update the content of the control ? There is updateValue() but you have to manually set the value in all those cases.

There is also a similar case when you update the selectbox options after the form building, it will show a selected value in the selectedbox, while the control value would be null, any ideas on how to deal with this ?

like image 239
Silencer Avatar asked Feb 23 '16 13:02

Silencer


People also ask

Does patchValue set dirty?

Bookmark this question.


2 Answers

In Angular 2 Final (RC5+) there are new APIs for updating form values. The patchValue() API method supports partial form updates, where we only need to specify some of the fields:

this.form.patchValue({id: selected.id}) 

There is also the setValue() API method that needs an object with all the form fields. If there is a field missing, we will get an error.

like image 188
Angular University Avatar answered Sep 29 '22 17:09

Angular University


Update

as of latest Update of angular2 syntax will be like this

this.form.controls['power'].setValue('anthing here'); 
like image 28
Pardeep Jain Avatar answered Sep 29 '22 18:09

Pardeep Jain