Angular 2 remove blank option and select the first option only

Viewed 2351

I have an array defined in typeScript file

 statusList: string[] = ['YES','NO']

Now I am iterating through the array in HTML page

 <select id='status' [(ngModel)]="model.truckStatus" name = "status" #status = "ngModel" required>
    <option *ngFor = "let status of statusList">
 </select>

When I load the page by default I am getting an empty option, how to make the first value from an array to be selected by default?

2 Answers

One solution is to add the following line to the component ngOnInit() method:

this.model.truckStatus = this.statusList[0];

And if the statusList is not defined in the component class, we should remove the this keyword and import the statusList array.

Something like this. In attribute condition, you can set any function and check some properties.

<select id='status' 
        [(ngModel)]="model.truckStatus" 
        name = "status" 
        #status = "ngModel" 
        required>

    <option *ngFor = "let status of statusList"
            [attr.selected]="status === 'YES'">
 </select>
Related