如何通过Angular 2 observable加载数据后,在html选择选项中选择/ init第一个值?

时间:2022-03-08 19:44:34

I have an html select with options that looks like this:

我有一个html选项,其选项如下所示:

<select [(ngModel)]="role" (ngModelChange)="roleChanged($event)">
    <option *ngFor="#role of roles" [ngValue]="role">{{role.Name}}</option>
</select>

roles[] gets assigned in a subscribe of an observable from my service. Everything is working fine except the select is empty initially even after roles[] is loaded. I would like the select drop down to display the first option immediately when roles[] is loaded from the service. And then have that change "role" too.

roles []在我的服务的可观察的订阅中分配。一切正常,除非加载角色[]后,select最初为空。我希望选择下拉列表在从服务加载角色[]时立即显示第一个选项。然后改变“角色”。

I'm thinking either using ngInit on the select, or the option, but can't seem to get it to work. Also I thought about assigning role in the component after the observable is returned but I can't figure that out / know if that's possible because roles[0] is always null before roles[] is loaded.

我想在选择或选项上使用ngInit,但似乎无法使它工作。我还想到在返回observable之后在组件中分配角色但是我无法弄清楚/知道这是否可能,因为在加载角色[]之前,角色[0]始终为空。

Here's the subscribe code if that is important:

这是订阅代码,如果这很重要:

 getDivisonTeamRoles() {
this._divisonProposalService.getDivisionTeamRoles()
                 .subscribe(
                   roles => this.roles = roles,
                   error =>  this.errorMessage = <any>error);

}

}

1 个解决方案

#1


0  

I figured it out. In the subscribe () function you can add multiple lines of code there and call functions, assign other variables, etc. Like so..

我想到了。在subscribe()函数中,您可以在那里添加多行代码并调用函数,分配其他变量等。如此...

.subscribe(
                   roles => { 
                     this.roles = roles;
                     this.role = this.roles[0]; 
                     this.getEmployeesByRole();
                    },
                   error =>  this.errorMessage = <any>error);

#1


0  

I figured it out. In the subscribe () function you can add multiple lines of code there and call functions, assign other variables, etc. Like so..

我想到了。在subscribe()函数中,您可以在那里添加多行代码并调用函数,分配其他变量等。如此...

.subscribe(
                   roles => { 
                     this.roles = roles;
                     this.role = this.roles[0]; 
                     this.getEmployeesByRole();
                    },
                   error =>  this.errorMessage = <any>error);