在 Angular 中,如何进一步跳过 ngIf 检查变量是否为 null,在模板中
In Angular, how to skip further ngIf check if a variable is null, in template
我在模板中有这个:
<div class="icon-action"
*ngIf="node == null ? false : node.data && node.data.name && !node.parent.data.virtual"
(click)="delete(node)">
<img src="./assets/img/cross.png">
</div>
但即使正确检查了节点,有时我仍然会收到错误消息:
TypeError: Cannot read properties of null (reading 'data')
false不应该直接返回吗?不知何故,angular 继续检查值 node.data,我不希望它这样做,因为如果它这样做,它会抛出错误。我尝试了多种检查 null 的方法,但 none 有效。我试过了
*ngIf = "node && node.data && node.data.name && !node.parent.data.virtual)"
和
*ngIf = "node == null ? false : node.data && node.data.name && !node.parent.data.virtual"
和
*ngIf = "node !=null && node.data && node.data.name && !node.parent.data.virtual"
每次我都遇到同样的错误
TypeError: Cannot read properties of null (reading 'data')
如何解决?
您可以简化您的条件,也可以使用 null chaining operator ?
来消除错误。这样,您的 ngIf
可以看起来像这样:
<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:
你确实在保护自己不访问 null node
上的 data
,但我没有看到任何代码检查 node.parent
是否为 null,错误可能来自 node.parent.data
.
我在模板中有这个:
<div class="icon-action"
*ngIf="node == null ? false : node.data && node.data.name && !node.parent.data.virtual"
(click)="delete(node)">
<img src="./assets/img/cross.png">
</div>
但即使正确检查了节点,有时我仍然会收到错误消息:
TypeError: Cannot read properties of null (reading 'data')
false不应该直接返回吗?不知何故,angular 继续检查值 node.data,我不希望它这样做,因为如果它这样做,它会抛出错误。我尝试了多种检查 null 的方法,但 none 有效。我试过了
*ngIf = "node && node.data && node.data.name && !node.parent.data.virtual)"
和
*ngIf = "node == null ? false : node.data && node.data.name && !node.parent.data.virtual"
和
*ngIf = "node !=null && node.data && node.data.name && !node.parent.data.virtual"
每次我都遇到同样的错误
TypeError: Cannot read properties of null (reading 'data')
如何解决?
您可以简化您的条件,也可以使用 null chaining operator ?
来消除错误。这样,您的 ngIf
可以看起来像这样:
<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:
你确实在保护自己不访问 null node
上的 data
,但我没有看到任何代码检查 node.parent
是否为 null,错误可能来自 node.parent.data
.