How to remove the previously selected option from a drop-down menu in a table?

前端 未结 2 854
广开言路
广开言路 2020-12-02 02:38

I am making a project on angular 7.It has a table with a column having dropdowns. The dropdown contains various languages. When a language is selected in a particular row, t

2条回答
  •  星月不相逢
    2020-12-02 03:15

    you can solve the problem by holding a set of selected languages and display options conditionally based on whether an option/language is selected before or not.

    create a Set to hold selected langs

    selectedLangs = new Set();

    create a view query to get a list of all select elements

    @ViewChildren("selectLang") langSelects: QueryList>;

    whenever a selection is made/changed on any of the select elements re-populate the selectedLangs set

      selected() {
        this.selectedLangs.clear();
        this.langSelects.forEach(ls => {
          const selectedVal = ls.nativeElement.value;
          if (selectedVal && selectedVal !== "undefined") this.selectedLangs.add(selectedVal);
        });
     }
    

    whenever a field is deleted just remove that language from selectedLangs

      deleteFieldValue(index: number, lang: string) {
        this.selectedLangs.delete(lang);
        this.fieldArray.splice(index, 1);
      }
    

    and when displaying options for a select check if it is currently selected on current select or already selected in another select *ngIf="selectLang.value === lang.name || !isSelected(lang.name)"

    
      
    
    

    where isSelected is defined as

      isSelected(lang: string) {
        return this.selectedLangs.has(lang);
      }
    

    here is a working demo with full source https://stackblitz.com/edit/angular-dqvvf5

提交回复
热议问题