0

I think I have a fundamental flaw in my attempt to bind a select element.

If I bind my select like so [(ngModel)]="selectedPrivilege" the select starts with nothing selected. If I remove the model binding, the [selected] attribute works and the appropriate option is selected, but with no model binding the (ngModelChange) no longer works.

I'm assuming I'm doing something stupid here.

  <div class="form-group">
      <label for="privilegeDDL">Privilege</label>
      <select  *ngIf="privileges.length > 0" class="form-control"  id="privilegeDDL" required  [(ngModel)]="selectedPrivilege" (ngModelChange)="onPrivilegeChange($event)"> 
        <option *ngFor="let p of privileges" [ngValue]="p" [selected]="p.level===user.privilege.level"> {{p.name}}</option>
      </select>
  </div>
Chris
  • 679
  • 1
  • 11
  • 26

1 Answers1

0

You should assign an initial value to selectedPrivilege equal to one of the possible values that an option can take, in order to avoid displaying an empty select.
One extra thing, you should bind the ngValue of the option either to p.level or p.name.
You can't simply bind a value of a native HTML option element to p because it is a complex object, from what I understood from you code.
So technically if you bind ngModel to p.level, you should set selectedPrivilege to one of the possible values that a level can take.
Here is a working example:

@Component({
  selector: 'exmaple',
  template: `
    <div class="form-group">
      <label>Privilege</label>
      <select [(ngModel)]="selectedPrivilege" (ngModelChange)="onPrivilegeChange($event)">
        <option *ngFor="let p of privileges" [ngValue]="p.level"> {{p.name}}</option>
      </select>
    </div>
  `,
})

export class Example {

  privileges = [
    {
      name: 'Option 1',
      level: '1',
    },
    {
      name: 'Option 2',
      level: '2',
    },
    {
      name: 'Option 3',
      level: '3',
    },
  ];

  public selectedPrivilege = '1';

  public onPrivilegeChange(value: any) {

    // Making sure that the two-way data binding works properly
    console.log('select value', value);
    console.log('selectedPrivilege', this.selectedPrivilege);
  }

}
Unsinkable Sam
  • 3,809
  • 1
  • 10
  • 18
  • This page is editing a object that generally is loaded after the drop down options are loaded. I ended up having to bind the select to a standalone 'privilege' object. When the object being edited and the select options are both loaded, the correct option gets selected, but I had to also assign the standalone privilege property to the privilege property of the object being edited as well, and then it worked. Probably just an oddity in my application flow... – Chris Nov 09 '17 at 13:47