Angular2 [selected] not working to set default value?

I am trying to set a default value for my selection, so I tried

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

something like that

but it didn’t work.

People said that [selected] no longer works, so I also tried [attr.selected], but it didn't work.

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 to set default option for selection?

+6
source share
4 answers

You need to do something like this:

In the 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' 
+8
source

You are comparing options to choose with compareWith property compareWith If you use compareWith 4, it may not work 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 solutions at this link.

+3
source

Here is my solution:

An example of time zones. From the backend, I got the following object:

 activeItem = { "timezone": { "timeZoneHolder": "Europe", "region": "Europe/Paris (CEST)", "UTC": "UTC+1" }} 

And the same element from my model looks a little different, as the source changes:

 { "timeZoneHolder": "France", "region": "Europe/Paris", "UTC": "UTC +01:00" } 

As you can see, a little different.

So here is my model:

 timeZones = [{ "timeZoneHolder": "France", "region": "Europe/Paris", "UTC": "UTC +01:00" }, { "timeZoneHolder": "French Polynesia", "region": "Pacific/Gambier", "UTC": "UTC -09:00" }] 

And here is the inscription for choice, it works like a charm:

 <select id="timezone" name="timezone" [(ngModel)]="activeItem.timezone"> <option [ngValue]="activeItem.timezone" [selected]="true" disabled hidden>{{activeItem.timezone.region}}</option> <option *ngFor="let timeZone of timeZones" [ngValue]="{timeZoneHolder: timeZone.countryName, region: timeZone.timeZone, UTC: timeZone.UTC}"> {{timeZone.timeZone}} </option> 

Enjoy :)

0
source

This does not work because your choice must have the [(ngModel)] attribute.

You just need to set this value to the one you want to choose, and you should be fine.

-1
source

Source: https://habr.com/ru/post/1268900/


All Articles