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]="">{{ }}</option>

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?


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.

  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.text</option>

Answered By – MeTTe

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.