簡體   English   中英

Angular2如果json對象中有空值,如何使用ngIf顯示其他文本?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM