ng如果不使用ng-template

时间:2017-11-16 12:29:53

标签: angular angular-components

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

---这是在Home.Component.HTML

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

----这是在HomeComponent

   isSummaryViewVisbile: boolean = true;

上面的代码不起作用,它总是隐藏模板,虽然我指的是真的。

提前致谢。

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

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