how to best conditional template show in angular 4

左心房为你撑大大i 提交于 2019-12-30 04:24:06

问题


currently, i am practiced angular 4. when a normal user view this then show public content When A Registered user enter the web page then show edit or some content. how to the best practices show conditionally template Or Some Html Contents Example:

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

actually, i want to know how to the best.


回答1:


In angular 4 you can use if.. else.. structure for html templates

You can use it in this way:

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

but in your case, the prettiest solutions will be if... then... else... conditional

<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>



回答2:


NgIf is a structural directive. That means your component would be destroyed when the expression becomes false.

So if your component is often destroyed and created again than this can be an issue. In this case the [hidden] directive should be considered. It only sets display:none. In this case your component would not be destroyed.

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



回答3:


use NgIf with else condition

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

<ng-template #Other> some Content here .....</ng-template>


来源:https://stackoverflow.com/questions/46770046/how-to-best-conditional-template-show-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!