* ng如果即使为假也仍在发布

问题描述 投票:0回答:1

在我的HTML中,我遇到了一个问题,即使if语句为false,* ngIf仍在创建空对象。我尝试了一些在网上找到的解决方案,但在我追赶中似乎无法使用。有什么解决办法,其中ngIf仅打印匹配的值?

这是我的代码的示例:

<ng-container *ngFor="let test of testing" >
   <div *ngIf="test.name === null">
      <p>Testing..</p>
   </div>
</ng-container>

编辑

为了提供更好的解释,当程序检查值时,即使值!= NULL,它也会添加一个空的div框。我要问的是是否存在某些东西,以便不会创建这些空的div,而只会创建匹配的值。

This is what I'm seeing from the inspect element

angular angular7
1个回答
0
投票

因为您正在循环testing,它在测试中仍会循环进行每个角度,然后将决定隐藏内容。

所以在页面上您应该只看到名称,但是如果您检查时看到带有*ngIf=false的空div,这是正常现象,并不意味着它们实际上在页面上呈现。

[如果由于某些原因您仍然不希望检查时显示这些空的div ...一种解决方法是从中过滤掉没有名称的test和从那里过滤出的*ngFor

。ts

filterTesting() {
  return this.testing.filter(x => !x.name);
}

html

<ng-container *ngFor="let test of filterTesting()" >
   <div>
      <p>Testing..</p>
   </div>
</ng-container>
© www.soinside.com 2019 - 2024. All rights reserved.