Search code examples
javascriptangularangular-ngselect

How to get addressibility to individual Angular components?


Environment: Angular 7 using the ng-select component.

Scenario: A *ngFor which creates a list of ng-select components as follows:

<div *ngFor="let address of addresses">
  <ng-select    
     [items]="address.cities"
     bindLabel="name"
     bindValue="id">
  </ng-select>
</div>

The ng-select component has methods which I need to call. How do I get each instance of ngSelect instance in order to call those methods from the model side.

I am able to see the decomposed htmlelements in the DOM but I don't want to traverse the DOM I just want to call certain ng-select methods but don't know how to get an instance of the component from the model.

An example of a method call would be:

instanceOfNgSelect.HandleClear();

I would want access to any of the instances created from the *ngFor...


Solution

  • Given:

    <div *ngFor="let address of addresses">
      <ng-select    
         [items]="address.cities"
         bindLabel="name"
         bindValue="id">
      </ng-select>
    </div>
    

    The best way to get addressibility to any of the ng-selects above is in the Model using the ViewChildren decorator:

    @ViewChildren(NgSelectComponent) NgSelectComponents: QueryList<NgSelectComponent>;
    

    Then in ngAfterViewInit():

      this.NgSelectComponents.forEach(ngselect=>{
         debugger;
        });