Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Reactive Forms: update select list on value changes

I have an Angular 2 form built using ReactiveForms. The form contains 2 select elements. The first one contains a list of vehicle makes. When a make is selected from the list, the second select element should show the models belonging to that make.

I've been playing around with valueChanges, but I can't seem to get the second(child) select element to contain the models for the selected make. When both fields are just simple input elements, reacting on valueChanges does in fact update the model input element (using the setValue on the model FormControl). See below code sample for simple input fields.

Is it even possible to accomplish this with Reactive Forms?

this.vehicleForm.controls['make'].valueChanges.subscribe((value) => {
  console.log(value);
  this.vehicleForm.controls['model'].setValue('Some Value');
});

In this case the 'value' is in fact the selected make object.

like image 894
supercell Avatar asked Sep 17 '26 19:09

supercell


1 Answers

You can use variable to store models you need to display in it and then use NgFor directive to display them in select list:

<select class="form-control" formControlName="models">
    <option *ngFor="let m of models" [value]="m">{{m}}</option>
</select>

And in your component:

this.vehicleForm.controls['make'].valueChanges.subscribe((value) => {
  console.log(value);
  this.models = ... // here you add models to variable models based on selected make
});

This way, every time models variable is changed, those changes will be reflected in your dropdown list.

like image 122
Stefan Svrkota Avatar answered Sep 19 '26 09:09

Stefan Svrkota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!