1

I'm generating a with *ngFor which doesn't allow me to directly set a "selected" attribute, what is the correct way to do that? I would like the last option to be selected but it doesn't really matter.

<select>
  <option
    *ngFor="let searchType of dateSearchTypeGroup"
    [ngValue]="searchType"
    (click)="onSelect(searchType)"
  >
    {{ searchType.viewValue }}
  </option>
</select>

EDIT: thank you for your answers but nothing made it. Iv'e found another solution: as the list i'm iterating on to generate the dropdown list is defined as an array i just set the selected value to the first row of the array:

dateSearchTypeGroup;
  selectedSearchType: DateSearchType;

  constructor() {
    this.dateSearchTypeGroup = dateSearchTypeGroup;
    this.selectedSearchType = this.dateSearchTypeGroup[0];
  }

And it works just fine.

Mechanizen
  • 99
  • 9

2 Answers2

2

if default value is on the basis of index or it is pre defined.

<select>
  <option
    *ngFor="let searchType of dateSearchTypeGroup; #i = index"
    [ngValue]="searchType"
    [selected]="i == 0"
    (click)="onSelect(searchType)">
    {{ searchType.viewValue }}
  </option>
</select>

if your default value is based upon some logic then

HTML

  <select>
      <option
        *ngFor="let searchType of dateSearchTypeGroup; #i = index"
        [ngValue]="searchType"
        [selected]="searchType === defaultValue"
        (click)="onSelect(searchType)">
        {{ searchType.viewValue }}
      </option>
    </select>

JS/Typescript

// *let assume your array is like this.*

dateSearchTypeGroup = [41, 42, 47, 48];

// *your logic or api call here*

defaultValue = 47;

you can also use ngModel on select tag.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Storytellerr
  • 642
  • 3
  • 18
1
public searchTypeModel;
...
ngOnInit() {
   this.searchTypeModel = this.dateSearchTypeGroup[this.dateSearchTypeGroup.length - 1];
}
<select [ngModel]="searchTypeModel">
  <option
    *ngFor="let searchType of dateSearchTypeGroup"
    [ngValue]="searchType"
    (click)="onSelect(searchType)"
  >
    {{ searchType.viewValue }}
  </option>
</select>
critrange
  • 5,652
  • 2
  • 16
  • 47