[英]Angular2 How can I use ngIf correctly to show some text only when there's no data from server?
[英]Angular2 How to use ngIf to show some other text if there's empty value in json Object?
嗨,我在理解ngIf時遇到問題。
目前我有的json對象
Profile:{
0:{name: 'Jen',
intro:'',
gender:'female',
age:'1992'},
1:{name: 'John',
intro:'Hi',
gender:'male',
age:'1988'}
}
第一個對象的簡介是空字符串,當它具有空字符串時,我要顯示“用戶尚未編寫”。
我嘗試像這樣使用ngIf,但是這當然行不通。 我該怎么辦?
<div *ngFor="let p of Profile">
<p class="fontstyle2">
{{p.intro}}
</p>
<p class="fontstyle2" *ngIf="p.intro=''">
The user hasn't written it yet
</p>
</div>
應該是==不是=
<p class="fontstyle2" *ngIf="p.intro==''">
The user hasn't written it yet
</p>
ngIf
使用JavaScript語法進行比較,因此您可以使用p.intro === ''
或僅使用!p.intro
因為空字符串是虛假的。
另一件事是,您可能只想顯示一種替代方案,因此您應在兩種ngIf
中均使用ngIf
:
<div *ngFor="let p of Profile">
<p class="fontstyle2" *ngIf="p.intro">
{{p.intro}}
</p>
<p class="fontstyle2" *ngIf="!p.intro">
The user hasn't written it yet
</p>
</div>
另一種選擇是采用這種方式:
<div *ngFor="let p of Profile">
<p class="fontstyle2">
{{p.intro? p.intro : "The user hasn't written it yet"}}
</p>
正如這里許多人所說的,您需要使用===
而不是僅僅在條件上使用=
。
<div *ngFor="let p of Profile">
<p class="fontstyle2">
{{p.intro}}
</p>
<p class="fontstyle2" *ngIf="p.intro===''">
The user hasn't written it yet
</p>
</div>
或者您可以簡單地檢查!
<div *ngFor="let p of Profile">
<p class="fontstyle2">
{{p.intro}}
</p>
<p class="fontstyle2" *ngIf="!p.intro">
The user hasn't written it yet
</p>
</div>
您想顯示Intro為空白時用戶尚未編寫 ,如果非空白, 則要顯示Intro的值
為此,您可以使用以下代碼段:
<div *ngFor="let p of Profile">
<p class="fontstyle2" *ngIf="p.intro!=''">
{{p.intro}}
</p>
<p class="fontstyle2" *ngIf="p.intro===''">
The user hasn't written it yet
</p>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.