简体   繁体   中英

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.

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.

As a simple extension of what was said before, the listener of the form in the component needs to go somewhere at the initialization:

onInit(){
  //Fill in makes nd intialize the form
  onChange()
}

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

This is also a good example of how to use Reactive Model Form: https://codecraft.tv/courses/angular/forms/reactive-model-form/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM