首页 > 解决方案 > ng-option 未从异步调用更新

问题描述

我有一个从异步调用加载的选择元素的选项列表。调用已成功执行,但选择未更新...

html

<select ng-model="selectedCommand"
        ng-options="command as command.name group by command.group for command in commands" >
    <option value="">-- Please select --</option>
</select>

home.component.ts

populateCommands(context, dataService) {
    dataService.getCommands()
        .do(console.log)
        .mergeMap(Observable.from)
        .mergeMap(group => {
            return Observable.from(group.commands)
                .map(command => {
                    command.group = group.name;
                    return command;
                })
        }).pipe(toArray())
        .subscribe(commands => {
            console.log(commands);
            context.commands = commands;
        });
}

ngOnInit() {
    var dataService = this.dataService;
    var populateCommands = this.populateCommands;
    var context = this;
    this.data.getLoggedInUser()
        .do(function() { populateCommands(context, dataService);})
        .subscribe(user => {
            this.loggedInUser = user;
        })
    }

有没有办法通过 ng-options 更新选择?


以下作品:

<select #command="ngModel" required class="custom-select geant-text-small"
        [(ngModel)]="selectedCommand" name="command"
        (click)="onTouched()">
  <option value="">-- Select Command --</option>
  <optgroup label="{{group.name}}" *ngFor="let group of commandGroups$"> 
    <option [ngValue]="command" *ngFor="let command of group.commands">
      {{command.name}}
    </option>
  </optgroup>
</select>

标签: angulartypescript

解决方案


推荐阅读