Home > Back-end >  In Angular, how to skip further ngIf check if a variable is null, in template
In Angular, how to skip further ngIf check if a variable is null, in template

Time:11-17

I have this in the template:

<div 
          *ngIf="node == null ? false : node.data && node.data.name && !node.parent.data.virtual"
          (click)="delete(node)">
          <img src="./assets/img/cross.png">
</div>

but even if node is properly checked, I still sometimes get the error:

TypeError: Cannot read properties of null (reading 'data')

Shouldn't the false just be returned? Somehow, angular proceeds to check for the value node.data, and I don't want it to, because it throws an error if it does. I tried many ways of checking for null, but none worked. I tried

*ngIf = "node && node.data && node.data.name && !node.parent.data.virtual)"

and

*ngIf = "node == null ? false : node.data && node.data.name && !node.parent.data.virtual"

and

*ngIf = "node !=null && node.data && node.data.name && !node.parent.data.virtual"

every time I am getting the same error

TypeError: Cannot read properties of null (reading 'data')

How to resolve this?

CodePudding user response:

You can simplify your condition, and also get rid of the error by using the null chaining operator ?. With that, your ngIf can look like this:

<div class="icon-action"
          *ngIf="node?.data?.name && !node?.parent?.data?.virtual"
          (click)="delete(node)">
          <img src="./assets/img/cross.png">
</div>

but even if node is properly checked, I still sometimes get the error:

You are indeed guarding yourself from accessing the data on a null node, but I did not see any piece of code checking if node.parent is null, and the error could be from node.parent.data.

  • Related