Search code examples
angularangular-materialangular-ngselect

How do I show extra option on checked checkbox?


I've got dropdown:

<ng-select [items]="items" bindLabel="name" ngModel name="dropdown" formControlName="dropdown" required></ng-select>

Here are items:

 items = [
    {
      id: 1,
      name: 'Option 1'
    }, 
    {
      id: 2,
      name: 'Option 2'
    }, 
    {
      id: 3,
      name: 'Option 3'
    }, 
    { //extra option
      id: 4,
      name: 'Option 4'
    },
  ]

I want the extra item (option 4) to be hidden. When he user click on checkbox, the extra option shows up. How do I do that?

My checkbox:

<mat-checkbox class="example-margin" ngModel name="checkbox" formControlName="checkbox">Show hidden option!</mat-checkbox>

Thanks in advance!


Solution

  • Just add additional array itemsToShow which will be used in ng-select. Original array will be used just as a data source. Then on checkbox change assign to itemsToShow the original array or filtered one by id field (depending on the current checkbox value).

    Component:

    export class DemoComponent implements OnInit {
        checkbox = new FormControl(false);
    
        items = [
            { id: 1, name: 'Option 1' },
            { id: 2, name: 'Option 2' },
            { id: 3, name: 'Option 3' },
            { id: 4, name: 'Option 4'},
        ];
    
        itemsToShow = [];
        itemIdToHide = 4;
    
        ngOnInit(): void {
            this.itemsToShow = this.getFilteredItems([this.itemIdToHide]);
    
            this.checkbox.valueChanges.subscribe((checked) => {
                if (checked) {
                    this.itemsToShow = [...this.items];
                } else {
                    this.itemsToShow = this.getFilteredItems([this.itemIdToHide]);
                }
            });
        }
    
        private getFilteredItems(idsToHide: number[]): { id: number; name: string }[] {
            return this.items.filter((item) => !idsToHide.includes(item.id));
        }
    }
    

    Template:

    <ng-select [items]="itemsToShow" bindLabel="name" ngModel name="dropdown" formControlName="dropdown" required></ng-select>
    <mat-checkbox class="example-margin" [formControl]="checkbox">Show hidden option!</mat-checkbox>
    
    

    Note, getFilteredItems() method can filter by multiple ids.