简体   繁体   中英

How to set initial value for select element in Angular ngrx?

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?

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)
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM