angularangular2-ngmodel

How to show placeholder (empty option) in select control in Angular 2?


I have this code in my template:

<select [ngModel]="selectedSubSectionId" (ngModelChange)="onSubSectionChange($event)">
  <option *ngFor="let subSection of event.subSections" [ngValue]="subSection.id">{{ subSection.name }}</option>
</select>

In my component:

public selectedSubSectionId: any;

public onSubSectionChange(subSectionId: any) {
  // some code I execute after ngModel changes.
}

This works ok, but at the beginning I have an empty box. I want to show a placeholder message there. How can I do this using ngModel?


Solution

  • My solution:

    In the component typescript file I add a property selectUndefinedOptionValue that I don't initialize and in the html I add the undefinedSelectOptionValue as value of the placeholder option. This solution works for both number and string model properties.

    @Component({
      selector: 'some-component-selector',
      templateUrl:'url to template',
    })
    export class SomeComponent implements OnInit {
        private selectUndefinedOptionValue:any;
        private someObject:SomeObject;
        
        ngOnInit() {
          someObject = new SomeObject();
        }
    }
    <select [(ngModel)]="someObject.somePropertyId">
      <option disabled hidden [value]="selectUndefinedOptionValue">-- select --</option>
      <option *ngFor="let option of options" [value]="option.id">option.text</option>
    </select>