Angular4: select [selected] not work for the first time

Galina picture Galina · Jan 17, 2018 · Viewed 8k times · Source

There is a code:

<select name="department" class="form-control select" [(ngModel)]="departments" formControlName="departmentControl">    
    <option *ngFor="let department of departments" [ngValue]="department" [selected]="department.id == this.departmentid">
      {{ department.name }}
    </option>
  </select>

and function:

isSelected(department): boolean {
  debugger;
  return department.id == this.departmentid;
}

department - is a nested component for user-detail component. After I select a user-detail component for the first time, department not selected. But for second time everything works correctly. Where is a mistake?

Answer

Vivek Doshi picture Vivek Doshi · Jan 17, 2018

There is no need of : [selected]="department.id == this.departmentid" as you are using [(ngModel)]

Change [(ngModel)]="departments" to [(ngModel)]="departmentid"

Change [ngValue]="department" to [ngValue]="department.id"

Finally it should look like this :

<select name="department" class="form-control select" [(ngModel)]="departmentid" formControlName="departmentControl">    
    <option *ngFor="let department of departments" [ngValue]="department.id" >
        {{ department.name }}
    </option>
</select>

WORKING DEMO