I'm having trouble getting using *ngIf/else statements to work. Here is the setup:
<div *ngFor="let sub of day">
<p>{{ sub.subject }}</p>
<button type="button" *ngIf="sub.subject; else showElse" routerLink="/day" (click)="viewIndividual(day)" class="btn btn-{{colors[i]}}">View {{ daysBetween[i] | date:'EEEE' }}'s Plan</button>
<ng-template #showElse>
<a type="button" class="btn btn-primary">Add a Lesson</a>
</ng-template>
</div>
The issue is my truthy statement is rendering (the button with View {{ daysBetween[i] | date:'EEEE' }}'s Plan
) on it, but my falsy value (the ng-template
) is not. I've looked at a couple tutorials and I thought I am doing it right, but I've only been studying Angular4 for a few days now. Please help!
You could either use a ngSwitch
or, as you only have two cases, go directly for two ngIf
:
<div *ngFor="let sub of day">
<p>{{ sub.subject }}</p>
<button *ngIf="sub.subject" type="button" routerLink="/day" (click)="viewIndividual(day)" class="btn btn-{{colors[i]}}">View {{ daysBetween[i] | date:'EEEE' }}'s Plan</button>
<a *ngIf="!sub.subject" type="button" class="btn btn-primary">Add a Lesson</a>
</div>
I think you should check your *ngIf condition once again. I have tried same in my code it is working.
TestObj = [
{
category : 'Test'
}, {
category : 'Test1'
}
]
HTML Code :
<div *ngFor="let key of TestObj">
<p *ngIf="key.subcategory; else newText">** {{key.category}}</p>
<ng-template #newText>No category found</ng-template>
</div>
This is showing No category found
two times because of the condition.
Note : If you want to simplify condition you can do by checking subject condition in component and set flag true or false according to that. And use that flag in *ngIf .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.