【问题标题】:how to best conditional template show in angular 4如何在角度 4 中最好地显示条件模板
【发布时间】:2017-10-16 12:11:51
【问题描述】:

目前,我正在练习角度 4。当普通用户查看此内容时,会显示公共内容当注册用户进入网页时,会显示编辑或某些内容。最佳实践如何有条件地显示模板或一些 Html 内容示例:

<div *ngIf="isUser">
    some Content  here......
</div>
<div *ngIf="!isUser">
    some Content here .....
</div>

其实,我想知道如何做到最好。

【问题讨论】:

标签: angular angular-template


【解决方案1】:

在 Angular 4 中,您可以将 if.. else.. 结构用于 html 模板

你可以这样使用:

<div *ngIf="isUser; else otherContent">
    some Content  here......
</div>
<ng-template #otherContent>
    <div>
        some Content here .....
    </div>
</ng-template>

但在您的情况下,最漂亮的解决方案将是 if... then... else... 有条件的

<ng-container *ngIf="isUser; then someContent else otherContent"></ng-container>

<ng-template #someContent ><div>some content...</div></ng-template>
<ng-template #otherContent ><div>other content...</div></ng-template>

【讨论】:

  • 应该是&lt;div *ngIf="isUser; else otherContent,然后是&lt;ng-template #otherContent&gt;。没有# 应该放在div 中。
  • 我完全同意你的看法。我编辑了我的答案。谢谢
【解决方案2】:

NgIf 是一个structural directive。这意味着当表达式变为 false 时,您的组件将被销毁。

因此,如果您的组件经常被销毁并再次创建,那么这可能是一个问题。在这种情况下,应该考虑[hidden] 指令。它只设置display:none。在这种情况下,您的组件不会被销毁。

<div [hidden]="expression">{{val}}</div>

【讨论】:

    【解决方案3】:

    NgIf 与其他条件一起使用

    <div *ngIf="isUser;else Other">
        some Content  here......
    </div>
    
    <ng-template #Other> some Content here .....</ng-template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 2018-02-07
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多