javascriptangulartypescriptangular-ngselect

Ng-Select - Set multiple dropdown values


we are using NG-SELECT trying a create multiple forms with drop-down , we are trying to update the value of all dropdowns when one of the dropdown is updated but unable to find the correct node or configuration option to set it.

//reusable-form.component.ts
.. some inputs here
<ng-select 
      [searchable]="false"
      [clearable]="false"
      [(ngModel)]="selectedOption"
      placeholder="search"
      (change)="onSelect($event)"
    >
      <ng-option *ngFor="let data of datas; trackBy:userByName [value]="data.name">
      {{
        data.name
      }}
     </ng-option>
</ng-select>
 

we tried setting the option on change event as below, but the values are updated on rest of the drop-downs

onSelect(event){
    this.selectedOption = event ; // even though model already has the value in it
    this.cdref.detectchanges();
}

Solution

  • We can use @Output to emit an event outside the component with the select (selectionChange), when the value changes ngModelChange will fire, we use the emit method of the event emitter, to send the data up to the parent element.

    <ng-select
      [items]="accounts"
      bindLabel="name"
      bindValue="name"
      [searchable]="false"
      [(ngModel)]="selectedAccount"
      (ngModelChange)="selectionChange.emit($event)"
    >
    </ng-select>
    

    We define the @Output as below:

    export class GroupDefaultExampleComponent implements OnInit {
      @Input() index: string;
      @Output() selectionChange: EventEmitter<string> = new EventEmitter<string>();
    

    Now on the parent component, we listen for this event (selectionChange) using event binding () and call the selectAll method.

    We take a ViewChildren which you can think of as an array like structure of all the components GroupDefaultExampleComponent inside the parent.

    Using this viewchildren, we loop through the elements using forEach and set the selected property using the selected value.

    @Component({
      selector: 'app-component',
      template: `
          <h2>Need to set all values as same once selected in anyone of dropdowns</h2>
          <div style="margin-top:50px" *ngFor="let i of [1,2,3,4]">
            <group-default-example #group [index]="i" (selectionChange)="selectAll($event);">
            </group-default-example>
          </div>
        `,
    })
    export class AppComponent {
      @ViewChildren(GroupDefaultExampleComponent)
      groups: QueryList<GroupDefaultExampleComponent>;
    
      selectAll(selectedAccount: string) {
        this.groups.forEach((group: GroupDefaultExampleComponent) => {
          group.selectedAccount = selectedAccount;
        });
      }
    }
    

    Stackblitz Demo