Angular2 How to use ngIf to show some other text if there's empty value in json Object?
Solution 1
it should be == not =
<p class="fontstyle2" *ngIf="p.intro==''">
The user hasn't written it yet
</p>
Solution 2
ngIf
uses javascript syntax for comparisons so you can use p.intro === ''
or just !p.intro
since an empty string is falsy.
Another thing is that you'd probably want to display only one of the alternatives so you should use ngIf
in both:
<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>
Another option would be to do it in this way:
<div *ngFor="let p of Profile">
<p class="fontstyle2">
{{p.intro? p.intro : "The user hasn't written it yet"}}
</p>
Solution 3
you want to display The user hasn't written it yet when intro is blank and if its not blank then you want to display value of Intro
For this you can use following code snippet :
<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>
Lea
Updated on August 29, 2022Comments
-
Lea over 1 year
Hi I'm having trouble understanding ngIf.
Currently I have json object of
Profile:{ 0:{name: 'Jen', intro:'', gender:'female', age:'1992'}, 1:{name: 'John', intro:'Hi', gender:'male', age:'1988'} }
The first object's intro is empty string and when it has empty string I want to display 'The user hasn't written it yet'.
I tried using ngIf like this but of course this doesn't work. What should I do?
<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>