John
John

Reputation: 72

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

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

Upvotes: 0

Views: 757

Answers (3)

brubs
brubs

Reputation: 1357

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()

Upvotes: 1

Muhammad Ahsan
Muhammad Ahsan

Reputation: 134

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; }

Upvotes: 0

Related Questions