3

I am using the Table extension from PrimeNG for creating tables and including it in other components. I have the following code:

<p-table [value]="data" [columns]="settings.columns" [paginator]="true" [rows]="10" [rowsPerPageOptions]="[10,25,50,100]" [totalRecords]="total" [tableStyleClass]="'table animate__animated animate__fadeIn'" [autoLayout]="true" [pageLinks]="5" [loading]="loading"
    [(selection)]="selectedItems" #dt>

and in the ts file:

@Component({
    selector: "manager-grid",
    templateUrl: "./grid.component.html",
    styleUrls: ["./grid.component.scss"],
    encapsulation: ViewEncapsulation.None
})
export class GridComponent implements OnInit {

    public _data: Array<any>;
    public _settings: any;
    public _loading: boolean;
    public total = 100;
    public selectedItems: any[];
    public _columnFilters: any;
    @ViewChild('dt') table: Table;

I am including this component in other pages as follows :

<manager-grid  [data]="data" [settings]="tableSettings" [loading]="isLoading"></manager-grid>

The table will store selected rows in the selectedItems variable and I am accessing this in the parent component like :

@ViewChild(GridComponent) gridComponent: GridComponent;

const items = this.gridComponent.selectedItems;

In one page, I am using two instances of the same table component. For the first table, I am getting selected items. But for the second table, the variable is showing as undefined.

How can I fix this and get the selected items for the second table ?

Happy Coder
  • 4,255
  • 13
  • 75
  • 152

1 Answers1

3

If you have multiple instances of the component in the same page then you can use @ViewChildren rather than @ViewChild to access all instances of the component. So:

import { ViewChildren, QueryList } from '@angular/core';

@ViewChildren(GridComponent) components: QueryList<GridComponent>;

Then you can iterate through each component like:

this.components.forEach((grid) => { const items = grid.selectedItems })
Andy Gibson
  • 187
  • 2
  • 7
  • I have used this, but still getting the reference to the first child. I am opening the second grid in a modal. This might be the cause of the issue ? – Happy Coder Sep 26 '20 at 11:23