3 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個贊
角4和5:
使用else
:
<div *ngIf="isValid;else other_content"> content here ...</div><ng-template #other_content>other content here...</ng-template>
你也可以用then else
:
<div *ngIf="isValid;then content else other_content">here is ignored</div> <ng-template #content>content here...</ng-template><ng-template #other_content>other content here...</ng-template>
或then
單獨(dú):
<div *ngIf="isValid;then content"></div> <ng-template #content>content here...</ng-template>
演示:
細(xì)節(jié):
<ng-template>
:是Angular自己的<template>
標(biāo)簽實(shí)現(xiàn),根據(jù)MDN:
HTML
<template>
元素是一種用于保存客戶端內(nèi)容的機(jī)制,該內(nèi)容在加載頁面時(shí)不會呈現(xiàn),但隨后可以在運(yùn)行時(shí)使用JavaScript進(jìn)行實(shí)例化。

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個贊
在Angular 4.xx中 您可以以四種方式使用ngIf來實(shí)現(xiàn)簡單的if else過程:
只需使用If
<div *ngIf="isValid"> If isValid is true</div>
使用If with Else(請注意templateName)
<div *ngIf="isValid; else templateName"> If isValid is true</div><ng-template #templateName> If isValid is false</ng-template>
使用If with Then(請注意templateName)
<div *ngIf="isValid; then templateName"> Here is never showing</div><ng-template #templateName> If isValid is true</ng-template>
使用If with Then和Else
<div *ngIf="isValid; then thenTemplateName else elseTemplateName"> Here is never showing</div><ng-template #thenTemplateName> If isValid is true</ng-template><ng-template #elseTemplateName> If isValid is false</ng-template>
提示:ngIf計(jì)算表達(dá)式,然后 在表達(dá)式分別為truthy或falsy時(shí)將then或else模板呈現(xiàn)在其位置。通常是:
然后 template是ngIf的內(nèi)聯(lián)模板,除非綁定到不同的值。
除非綁定,否則else模板為空。

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個贊
為了使用observable,如果可觀察數(shù)組由數(shù)據(jù)組成,我通常會這樣做。
<div *ngIf="(observable$ | async) as listOfObject else emptyList"> <div > .... </div></div> <ng-template #emptyList> <div > ... </div></ng-template>
- 3 回答
- 0 關(guān)注
- 3519 瀏覽
添加回答
舉報(bào)