Reputation: 1181
In Angular4/ngrx, how do we set a value as selected option in select box?
The options are loaded via XHR. Both list of options / to be selected value is available in store.
Here is the template:
<select class="form-control" (change)="onSelectOperator($event.target.value)">
<option *ngFor="let operator of operator$ | async">{{operator.name}}</option>
</select>
Store:
export const initialState = {
operators: [], // to be loaded via XHR
selected: 'All'
};
Component:
ngOnInit() {
this.loadOperators();
// assign observable
this.operators$ = this.store.select(getOperators);
}
After load, selected
value in store should be set as initial value for the select box. This will be present in the XHR response list.
The angular 1 equivalent would be to use two way binding and set value to ng-model. How does this translate into Angular4/ngrx?
Upvotes: 0
Views: 2810
Reputation: 1757
Use route guards to for loading values; so when your component inits all state will be ready to serve you component
canActivate(): Observable<boolean> {
return this.checkStore().pipe(
switchMap(() => of(true)),
catchError((error) => of(false))
);
}
checkStore(): Observable<boolean> {
this.store.select(fromStore.selectAlbumsLoaded).subscribe((x) => console.log(x));
return this.store.select(fromStore.selectAlbumsLoaded).pipe(
tap(loaded => {
if (!loaded) {
this.store.dispatch(new fromStore.LoadAlbums());
}
}),
filter(loaded => loaded),
take(1)
);
Upvotes: 1