I have a select dropdown and I iterate the options from a list. I am trying to set as selected a separate option (as a default), in case of user is not selecting a value.
Here is how I am trying to implement that:
<select [(ngModel)]="book.pageLayout">
<option [value]="0" [attr.selected]="book.defaultLayoutId === null">No Default Layout</option>
<option *ngFor="let l of availableLayouts"
[value]="l.id"
[attr.selected]="book.pageLayout == l.id">
{{l?.name}}
</option>
</select>
I also tried:
<option [value]="0" selected="selected">No Default Layout</option>
and even:
<option [value]="0" selected="1==1">No Default Layout</option>
but none of the above worked.
Any help is welcome
Attribute selected will not help much if you are using ngModel then you can do easily with setting default value to the defined model.
<select [(ngModel)]="book.pageLayout">
<option value="">No Default Layout</option>
<option *ngFor="let l of availableLayouts" [value]="l.id">
{{l?.name}}
</option>
</select>
Then inside component.ts
public book: any = {
pageLayout: ''
}
Edit
To set default option we need to set pageLayout value to id instead of empty string.
public book: any = {
pageLayout: 1
}
public availableLayouts: any = [
{
name: "One",
id: 1
},
{
name: "Two",
id: 2
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With