0

I came across this post on another post asking this same question saying it's already answered however I can't seem to get it to work in my code. Inside of my component I have two variables defined like this.

MediaOptions: string[] = ['all', 'print', 'screen'];

DefaultOption: string = this.MediaOptions[0];

Inside my template I do this

<select [(ngModel)]="Value">

  <option
    *ngFor="let a of MediaOptions"
    [ngValue]="a"
    [selected]="a === DefaultOption ? true : null"
  >
    {{a}}
  </option>

</select>

this isn't working. I've tried the following as well

<select [(ngModel)]="Value">

  <option
    *ngFor="let a of MediaOptions; let i = index"
    [ngValue]="a"
    [selected]="i === 0 ? true : null"
  >{{a}}</option>

</select>
<select [(ngModel)]="Value">

  <option
    *ngFor="let a of MediaOptions"
    [ngValue]="a"
    [selected]="a === 'all'"
  >{{a}}</option>

</select>

I also switched back and forth with [selected] and [attr.selected] with each one. I tried removing the conditions like in the last example, none of them seem to work. Is there something that changed since that question was answered? What do we need to do to get it to work?

Update

I forgot to mention in the question that the Value property the [(ngModel)] is binding to is a setter function that looks like this.

set Value(val: any){
    this.MediaTypeControl = val;
    this.onChange(val);
    this.onTouch(val);
  }

This is inside of an Angular form where I'm using ControlValueAccessor to create custom inputs.

Optiq
  • 2,835
  • 4
  • 33
  • 68
  • 3
    I believe it is due to `[(ngModel)]="Value"` override the selected behavior. You should assign `DefaultOption` value to `Value`. Remove ``[(ngModel)]="Value"`` from `select` and you will see the `[selected]` attribute for option will work. – Yong Shun Aug 09 '22 at 04:01
  • 1
    check this https://stackblitz.com/edit/angular-ivy-mwggpd?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html – cfprabhu Aug 09 '22 at 04:07
  • I forgot to mention an important piece of info about the `Value` property being bound to, I just updated the question to show what's going on. – Optiq Aug 09 '22 at 04:19

1 Answers1

1

check this stackblitz example.

i think you forget to write a getter function.