When retrieving a response from an API, it will be received asynchronously.
To handle this situation, you can utilize the setValue
method on either your FormControl
or FormGroup
instance to establish default values.
An example of how this could be implemented is shown below:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { DataService } from './data.service';
@Component({
selector: 'select-multiple-example',
templateUrl: 'select-multiple-example.html',
styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
toppingList: string[] = [
'Extra cheese',
'Mushroom',
'Onion',
'Pepperoni',
'Sausage',
'Tomato'
];
selectedByDefault;
toppings: FormControl;
constructor(private dataService: DataService) {}
ngOnInit() {
this.toppings = new FormControl(this.selectedByDefault);
this.dataService.selectedValues$
.subscribe(values => this.toppings.setValue(values));
}
}
For further reference, here is a Functional Sample on StackBlitz.