Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

angular2 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...