Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 426
Leantraxxx Avatar asked Aug 02 '16 15:08

Leantraxxx


1 Answers

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>
like image 179
MeTTe Avatar answered Oct 06 '22 00:10

MeTTe