It appears that you are utilizing reactive forms based on the link provided.
To achieve your goal, pay attention to the valueChanges
observable, which triggers a new value whenever there is a change in the form control's value.
This emitted value allows us to update the options list for the second select
element.
In the app.component.ts file:
export class AppComponent {
public carsForm: FormGroup;
public cars$: Observable<any[]>;
public models$: Observable<any[]>;
private carFormControl = new FormControl("");
private modelFormControl = new FormControl("");
private carChangeSubscription: Subscription;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.carsForm = this.fb.group({
car: this.carFormControl,
model: this.modelFormControl
});
this.cars$ = this.getCars();
this.carChangeSubscription = this.carFormControl.valueChanges.subscribe(
carId => {
this.modelFormControl.setValue("");
this.models$ = this.getModels(+carId);
}
);
}
ngOnDestroy() {
this.carChangeSubscription.unsubscribe();
}
private getCars() {
return of([
{
id: 1,
name: "MERCEDES-BENZ"
},
{
id: 2,
name: "VOLVO"
},
{
id: 3,
name: "AUDI"
},
{
id: 4,
name: "HONDA"
}
]);
}
private getModels(carId: number) {
return of([
{
id: 1,
carId: 1,
name: "SL55 AMG"
},
{
id: 2,
carId: 2,
name: "C70"
},
{
id: 3,
carId: 3,
name: "S4"
},
{
id: 4,
carId: 4,
name: "CR-V"
}
]).pipe(
map(models => {
return models.filter(x => x.carId === carId);
})
);
}
}
For the app.component.html file:
<form [formGroup]="carsForm">
<select formControlName="car">
<option value="">Please select</option>
<option *ngFor="let car of cars$ | async" [value]="car.id">
{{car.name}}
</option>
</select>
<br /><br />
<select formControlName="model">
<option value="">Please select</option>
<option *ngFor="let model of models$ | async" [value]="model.id">
{{model.name}}
</option>
</select>
</form>
The AsyncPipe
is used to subscribe to the two data observables.
We ensure to unsubscribe from the valueChanges
observable when the component is destroyed.