Set the selected attribute in a dropdown list if the condition is met in Angular2
Asked Answered
A

2

5

I have 2 objects in my project: a company and an user. I have a form where the user can update his profile. One of the things he can update is the country. Now to show the countries I use a dropdown list.

I want to set the selected attribute in the option where the name of the country is equal to the actual country of the user. (country.name==user.country)

This is what I have tried but It doesn't seem to work.

<select>
    <option *ngFor="#c of countries" [ngStyle]="setStyles()" [ngValue]="c">{{c.name}}</option>          
</select>

setStyles(){
    let styles;
    if (this.companies[i].name == this.user.country ) {
        styles = {
            'selected'
        } 
    return styles;
}
Aciniform answered 17/5, 2016 at 7:21 Comment(0)
L
9

I would try the following:

<select>
  <option *ngFor="#c of countries"
       [attr.selected]="c.name == user.country ? true : null" 
       [ngValue]="c">
    {{c.name}}
  </option>
</select>

I think that it's an attribute you need and not a style.

Leake answered 17/5, 2016 at 7:24 Comment(1)
Thanks it works, but not on every user, but I think I need to tweak some of my code.Aciniform
S
0

This is how I solved a similar problem:

<option 
   *ngFor="let option of checklistOptions"
   [selected]="option === mock.value" 
   [ngValue]="option">
   {{ option }}
</option>
Simper answered 9/9 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.