NgIf隐藏父母并显示孩子

时间:2017-07-06 05:12:58

标签: angular

我有一个我想要实现的案例,我不知道是否有可能。基本上我有类似的东西。

<div *ngIf = false>
...long code
    <div ngIf = true>
       ...long code
    </div>
</div>

理念是仅显示子组件并在某些条件下隐藏所有父组件。 我怎样才能实现这样的目标。

2 个答案:

答案 0 :(得分:1)

正如@Maximus建议的那样,您可以隐藏父级内容的一部分而不是父级本身。 像这样的东西

<div> <!-- the parent -->
        <div *ngIf ="!someVariable">  <!-- contents of the parent -->
        ...long code
    <div ngIf ="someVariable"> <!-- the child -->
       ...long code
    </div>
</div>

如果你要走这条路线,我认为更好的方法是删除父子关系,只有2个div。

     <div *ngIf ="!someVariable">  <!-- contents of the parent -->
        ...long code
     </div>
    <div ngIf ="someVariable"> <!-- the child -->
       ...long code
    </div>

我认为这要简单得多。希望这会有所帮助。

答案 1 :(得分:0)

您可以通过使用ng-template插座来完成此操作

<parent *ngIf="condition else child">
    <ng-container *ngTemplateOutlet="child"></ng-container>
</parent>
<ng-template #child>
    ...child contents
</ng-template>
相关问题