How to select/init first value in html select option after data loads thru Angular 2 observable?

Issue

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

<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.

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.

Here’s the subscribe code if that is important:

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

}

Solution

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(
                   roles => { 
                     this.roles = roles;
                     this.role = this.roles[0]; 
                     this.getEmployeesByRole();
                    },
                   error =>  this.errorMessage = <any>error);

Answered By – Kevin Quiring

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.