Home > Blockchain >  How do I call ngAfterViewInit() if specific condition is met
How do I call ngAfterViewInit() if specific condition is met

Time:10-21

Here is the reference code URL

so I have using the above code in my component.... but in my comonent table is inside ngcontainer which gets visible once some flag(e.g. visibleTabulardata) is set to true

<ng-container *ngIf='visibleTabulardata'> <!-- this gets visible after some specific condition
inside this table and mat-paginator code is used from the above URL
</ng-container>

Now they have used below code to initialize data across pages

 @ViewChild('paginator') paginator: MatPaginator;
  @ViewChild('paginatorPageSize') paginatorPageSize: MatPaginator;

  pageSizes = [3, 5, 7];

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSourceWithPageSize.paginator = this.paginatorPageSize;
  }

So and in my ts file one method is there which sets visibleTabulardata as true

enableTableData(){
this.visibleTabulardata =true;
}

I tried calling ngAfterViewInit() nside enableTableData() but it is not working

CodePudding user response:

ngAfterViewInit() is an Angular lifecycle hook and is not supposed to be called arbitrarily. The best way in your case is to move these assignments to a separate method and call this method from your hook and from enableTableData()

CodePudding user response:

you cannot call ngAfterViewInit by yourself as it's a life cycle hook triggered by angular itself. instead, make a method initPaginator and encapsulate paginator code in that call initPaginator where you want

initPaginator(){
 this.dataSource.paginator = this.paginator;
 this.dataSourceWithPageSize.paginator = this.paginatorPageSize; }

CodePudding user response:

By adding

<div  [hidden]="visibleTabulardata"> 
Based on a button click you hide/show the tabel and pagination.

https://stackblitz.com/edit/angular-mat-table-pagination-example-yhyftk?file=src/app/simple-mat-table/simple-mat-table.component.ts,src/app/simple-mat-table/simple-mat-table.component.html&file=src/app/simple-mat-table/simple-mat-table.component.html

  • Related