Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 293
Claudiu Matei Avatar asked Feb 07 '23 00:02

Claudiu Matei


1 Answers

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.

like image 84
Thierry Templier Avatar answered Feb 13 '23 05:02

Thierry Templier