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 ?
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With