formsdrop-down-menuangularng-style

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


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;
}

Solution

  • 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.