Reputation: 309
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.
Upvotes: 3
Views: 21252
Reputation: 24
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/
Upvotes: 0
Reputation: 50633
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.
Upvotes: 12