【问题标题】:ngIf not working with ng-templatengIf 不使用 ng-template
【发布时间】:2021-08-08 23:35:58
【问题描述】:

我想根据 Angular 4 中的布尔值显示或隐藏模板。下面是 HTML 和代码

--- 这是在 Home.Component.HTML 中

<ng-template [ngIf]="isSummaryViewVisbile" #pricebookView ></ng-template>

---- 这是在 HomeComponent 里面

   isSummaryViewVisbile: boolean = true;

上面的代码不起作用,它总是隐藏模板,尽管我分配的是 true。

提前致谢。

【问题讨论】:

  • 你有isSummaryViewVisbile,你确定其中一个没有被命名为isSummaryViewVisible(注意'visible'的正确拼写)
  • 很抱歉,拼写不正确,但两个文件中的内容相同。
  • 您为什么不使用专门为此目的而引入的&lt;ng-container&gt;
  • 这是一个笨蛋。我已经复制了你的代码,它工作正常。 plnkr.co/edit/6hbe0Z?p=preview

标签: angular angular-components


【解决方案1】:

ng-template 是一个用于渲染 HTML 的 Angular 元素。它永远不会直接显示。事实上,在渲染视图之前,Angular 会用注释替换 和它的内容。如果没有结构指令并且你只是将一些元素包装在一个 ng-template 中,这些元素就会消失。

<p>Hip!</p>
<ng-template>
  <p>Hip!</p> //would disappear
</ng-template>
<p>Hooray!</p>

所以下面的代码可以正常工作

isSummaryViewVisbile = true;

<ng-template [ngIf]="isSummaryViewVisbile" #pricebookView >
       Hello world.
</ng-template>

但是如果将 [ngIf] 替换为 *ngIf,则相同的代码将不起作用。

因为在内部,Angular 将 *ngIf 属性转换为 ng-template 元素,包裹在宿主元素周围。例如

<ng-template *ngIf="isSummaryViewVisbile" #pricebookView >
       Hello world.
</ng-template>

将转换为-

<ng-template [ngIf]="isSummaryViewVisbile">
      <ng-template #pricebookView >
           Hello world.
    </ng-template>
</ng-template>

现在我们可以看到,内部 ng-template 将始终隐藏它的内容。我希望这清楚。

演示:https://plnkr.co/edit/yB7PKx?p=preview

【讨论】:

    【解决方案2】:

    根据 Mohit 的回答/评论,您的代码是有效的...如果您要将内容分配给它应该显示的 ng-template 标记。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多