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