1

I have scenario where i need to populate list of values for a dropdown list in angular 7 app. But i should grey out the particular value from that list based on condition or flag.

Eg: I am populating alphabets in UI with drop down list (a to z letters)-> among them i need to disable letter "N" when user try to select that .

Can any one suggest me how we can do in angular 7

AKN
  • 33
  • 1
  • 9

2 Answers2

0
<ng-option [value]="item.id" [disabled]="item.disabled" *ngFor="let item of items">
                <img src="./assets/{{item.image}}" width="20px" height="20px"/>
                {{item.name}}
            </ng-option>

Used this Code

Malakiya sanjay
  • 208
  • 2
  • 12
0

It could be done by binding a dynamic value to [disabled] property.

Component:

export class AppComponent  {
  colors =  [
    {value: "Dark Green"},
    {value: "Red"},
    {value: "Dark Grey"},
    {value: "Beige"},
  ];

  fruits =  [
    {value: "Apple", disabled: false},
    {value: "Passion fruit", disabled: true},
    {value: "Dragon fruit", disabled: true},
    {value: "Orange", disabled: false},
  ];

  public ifColorDark(color: string): boolean {
    return color.indexOf('Dark' || 'dark') !== -1;
  }
}

Template:

<select type="number" [(ngModel)]="selectedItem">
  <option [disabled]="ifColorDark(color.value)" *ngFor="let color of colors" [ngValue]="color.value">{{ color.value }}</option>
</select>

<select type="number" [(ngModel)]="selectedItem">
  <option [disabled]="fruit.disabled" *ngFor="let fruit of fruits" [ngValue]="fruit.value">{{ fruit.value }}</option>
</select>

Working example: Stackblitz

ruth
  • 29,535
  • 4
  • 30
  • 57