I presume, because of the link you referenced, you're using reactive forms.
You want to look at the valueChanges observable, which emits a value each time our form control value changes.
By using the emitted value, we can fetch an updated list of options for our second select element.
app.component.ts:
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);
})
);
}
}
app.component.html
<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 subscribes to our two data observables.
We unsubscribe from the valueChanges observable when the component is destroyed.