Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 [selected] does not work to set up the default value?

I'm trying to set up default value for my selection so I tried

[selected]= "selected_choice == 'one'"

something like this

but this didn't work.

People said [selected] no longer works so I also tried [attr.selected] but didn't work as well..

this is my whole code for one select tag

  <select (change)="passValue3()" formControlName="school" class="form-control" required [(ngModel)]="selected_student" class="selectionbox">
    <option *ngIf="selected_student == undefined">학년 선택</option>
    <option *ngFor="let gradetype of gradeTypes" [ngValue]="gradetype" [attr.selected] = "gradetype.gradeType === 'Middle'">{{gradetype.gradeName}}</option>
</select>

How can I set up the default option for the select?

like image 894
Lea Avatar asked Jun 16 '17 08:06

Lea


2 Answers

You need to do something like this:

In Markup:

<select placeholder="Sample select" [(ngModel)]="selectedItem">
                    <option [value]="'all'">View All</option>
                    <option [value]="'item-1'">Item-1</option>
                    <option [value]="'item-2'">Item-2</option>
                </select>

In Component

  selectedItem='all'
like image 109
Ketan Akbari Avatar answered Nov 14 '22 06:11

Ketan Akbari


you compare options to select by compareWith property, If you are using angular 4, may be it will not working on angular 2.

HTML File :

<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">  
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>

TS File

byAnimal(item1,item2){
  return item1.type == item2.type;
}

One of the best solution from this link

like image 26
Vinit Solanki Avatar answered Nov 14 '22 06:11

Vinit Solanki