Reputation: 1583
Below is My Angular5 Code
<div class="section">
<h6 style="font-weight:bold">Select a Branch</h6>
<select [(ngModel)]='Schedule.Branch'>
<option *ngFor="let item of DataList;let i = index" value="{{item.Code}}" [selected]="i == 0">
{{item.Name}}
</option>
</select>
</div>
I saw a post on stackoverflow to set the selected option in Angular , same I tried in my code as
[selected]="i == 0 "
If I is equal to 0 means first option should be selected
i is defined in ngFor loop
*ngFor="let item of BranchList;let i = index"
but its not working, I also tried
[selected]="item.index == 0 "
But does not work , how can I set first option as selected ?
Upvotes: 0
Views: 1634
Reputation: 3934
[(ngModel)]='schedule.branch'
and [selected]="i == 0"
both are conflict. You use only one according to your faviour.
HTML
<div class="section">
<h6 style="font-weight:bold">Select a Branch</h6>
<select>
<option *ngFor="let item of this.dataList;let i = index" value="{{item.code}}" [selected]="i == 0">
{{item.name}}
</option>
</select>
</div>
Component
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular 5';
dataList: Array<any> = [];
schedule: { branch: '' };
constructor() {
this.dataList = [
{ code: 1, name: "shohel" },
{ code: 2, name: "rana" },
{ code: 3, name: "shipon" }
]
}
}
Upvotes: 1
Reputation: 86760
No need to bind with ngModel
if you are using selected
, code your should be like this
<div class="section">
<h6 style="font-weight:bold">Select a Branch</h6>
<select >
<option *ngFor="let item of this.dataList;let i = index" value="{{item.code}}" [selected]="i == 2">
{{item.name}}
</option>
</select>
</div>
Upvotes: 3