Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular set dropdown select option as default selected before iteration

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

like image 420
George George Avatar asked Sep 05 '26 03:09

George George


1 Answers

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
  }
]
like image 115
Javascript Hupp Technologies Avatar answered Sep 06 '26 20:09

Javascript Hupp Technologies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!