Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 650
Galina Avatar asked Dec 11 '22 08:12

Galina


2 Answers

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

like image 72
Vivek Doshi Avatar answered Dec 24 '22 06:12

Vivek Doshi


Your ngModel is wrong you should have it as departmentid and the ngValue should be the id of the department as below

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

Refer this answer for more information

like image 21
Aravind Avatar answered Dec 24 '22 06:12

Aravind