Kamal Chanda
Kamal Chanda

Reputation: 173

Angular 2 remove blank option and select the first option only

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?

Upvotes: 4

Views: 2429

Answers (2)

Mohamed Gara
Mohamed Gara

Reputation: 2935

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.

Upvotes: 1

Roman Skydan
Roman Skydan

Reputation: 5748

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>

Upvotes: 0

Related Questions