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

∥☆過路亽.° 提交于 2019-11-28 05:25:00

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>

I've the same question, and i found an example in this great website: Angular Quick Tip

also, i put the example below:

// template
<form #f="ngForm">
  <select name="state" [ngModel]="state">
    <option [ngValue]="null">Choose a state</option>
    <option *ngFor="let state of states" [ngValue]="state">
      {{ state.name }}
    </option>
  </select>
</form>

//component
state = null;

states = [
  {name: 'Arizona', code: 'AZ'},
  {name: 'California', code: 'CA'},
  {name: 'Colorado', code: 'CO'}
];

Also works with Reactive Forms, that's what i'm using:

// template
<div class="form-group">
  <select formControlName="category">
    <option [ngValue]="null">Select Category</option>
    <option *ngFor="let option of options" 
            [ngValue]="option">{{option.label}}</option>
  </select>
</div>

// component
options = [{ id: 1, label: 'Category One' }, { id: 2, label: 'Category Two' }];

form = new FormGroup({
  category: new FormControl(null, Validators.required)
});

Thanks to Netanel Basal to provide the answer

Serkan KONAKCI

Add empty option and set to 'undefined' also can be add for null value too

<select [(ngModel)]="barcode">
  <option value="undefined" disabled selected hidden>Select</option>
  <option value="null" disabled selected hidden>Select</option>
  <option *ngFor="let city of turkiye" [ngValue]="city.id">{{city.name}}</option>
</select>
Rodion Golovushkin

try this code:

<select [ngModel]="selectedSubSectionId? selectedSubSectionId : ''" (ngModelChange)="onSubSectionChange($event)">
   <option value="" disabled selected hidden>Placeholder</option>
   <option *ngFor="let subSection of event.subSections" [value]="subSection.id">{{ subSection.name }}</option>
</select>

Have you tried putting placeholder="Your placeholder string" inside the select or option tag?

I assume the string can be replaced with a variable if you don't want to hard code the string in your view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!