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
Try this
<option [value]="undefined" selected>No Default Layout</option>
, it should work.You can use FormControl from Angular Reactive Form.It is easy. Angular Docs About Reactive Form You need to import
reactive form
to you moduleThan you need to create FormControl in you component.ts
After this you need to set Form control to your element
select
in htmlIf you need default value of select you must create formControl with value for example:
In this case default value for select will be null.And options with value null will be selected in dropdawn.
In you case
new FormControl(0)
as default value.Attribute selected will not help much if you are using ngModel then you can do easily with setting default value to the defined model.
Then inside component.ts
Edit
To set default option we need to set pageLayout value to id instead of empty string.
You can try this
ng-selected="selected"
https://docs.angularjs.org/api/ng/directive/ngSelected