juanbits
juanbits

Reputation: 347

DOM undefined when the element is inside a *ngIf container

my problem is that i cant acces to a particular DOM element and their properties when the element is a children of a *ngIf container.

My case is: I a have a mat-table inside a div, the div have the *ngIf directive, and then i try to call mytable.renderRows() when my datasource changed, but i got an undefined value. I see this problem happens when the element is inside the ngIf directive, in other case i can access without problem.

<div *ngIf="!hasPermission" >
    <table mat-table #myTable [dataSource]="myDataSource">

and i have this on the .ts file:

export class MyComponent {

   hasPermission = true

   @ViewChild('myTable',{static:true}) myTable: MatTable<any>;

   constructor(){
      if(checkSomething == true){
          this.hasPermission = false
          this.myFunctionIfNotHavePermsissions()
      }
   }

   myFunctionIfNotHavePermsissions(){
      this.myTable.renderRows();
      // console.log(this.myTable); *NOTE: This output: undefined*
   }

}

For the moment, I fixed this problem, hidding the div using css, but i think this not the best solution, thanks in advance for your comments.

<div *ngIf="!hasPermission" >

to

<div [ngClass]="{ 'nodisplay': !hasPermission}" >

.nodisplay{display:none!important;}

Upvotes: 1

Views: 632

Answers (2)

miladfm
miladfm

Reputation: 1526

in constructor you the template is not ready and mat-table is not rendered.

add your logic in ngOnInit

export class MyComponent implements OnInit {

   hasPermission = true

   @ViewChild('myTable',{static:true}) myTable: MatTable<any>;


   constructor() {}


   ngOnInit() {
      if(checkSomething == true){
          this.hasPermission = false
          this.myFunctionIfNotHavePermsissions()
      }
   }

   myFunctionIfNotHavePermsissions(){
      this.myTable.renderRows();
      // console.log(this.myTable); *NOTE: This output: undefined*
   }

}

Upvotes: 1

Abhijit
Abhijit

Reputation: 412

I may don't know the actual reason behind it, but I think angular need a little time to first render whatever inside the ngIf element and then make available to DOM.

You can fix your issue by changing static to false here

@ViewChild('myTable', {static: false}) myTable: MatTable<any>;

and calling this.myFunctionIfNotHavePermsissions() inside a setTimeout

constructor(){
  if(checkSomething == true){
      this.hasPermission = false
      setTimeout(()=> this.myFunctionIfNotHavePermsissions());
  }
}

Upvotes: 1

Related Questions