Search code examples
angularangular-reactive-formsangular4-forms

Don't Allow Another Value In Dropdown To Be Selected in Angular


I have a simple problem. Is there a way that if i could select a value from a dropdown and then when i add another row, that selected dropdown value cannot be selected anymore? Only values that are not selected will be available in the dropdown? Here's the link to my stackblitz below:

https://stackblitz.com/edit/form-array-patch-mtiiee?file=app/app.component.ts

<div class="col-sm-12">
    <select class="form-control" formControlName="ingredientData">
        <option value="null" hidden>-- Select Ingredient --</option>
        <option *ngFor="let ingredient of ingredients" [ngValue]="ingredient">
            {{ingredient.name}}
        </option>
    </select>
</div>

Solution

  • You can check whether current option is already selected in value of form's rows form array and set disabled to corresponding select option.

    <option *ngFor="let ingredient of ingredients" [ngValue]="ingredient" [disabled]="isSelected(ingredient)">
    
    isSelected(ingredientData) {
      return this.addForm.get('rows').value.find(item => ingredientData === item.ingredientData);
    }
    

    Refer example.