I'm using Angular and I want to use *ngIf else
(available since version 4) in this example:
<div *ngIf="isValid">
content here ...
</div>
<div *ngIf="!isValid">
other content here...
</div>
Jak mogę osiągnąć to samo zachowanie za pomocą ngIf else
?
Angular 4 i 5:
użycie else
:
<div *ngIf="isValid;else other_content">
content here ...
</div>
<ng-template #other_content>other content here...</ng-template>
możesz również użyć 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>
lub samego then
:
<div *ngIf="isValid;then content"></div>
<ng-template #content>content here...</ng-template>
Demo :
[Plunker][1]
Szczegóły:
<ng-template>
: jest własną implementacją Angulara dla tagu <template>
, który jest zgodny z [MDN][2] :
Element HTML
<template>
jest mechanizmem do przechowywania po stronie klienta zawartość, która nie ma być renderowana, gdy strona jest ładowana, ale może następnie zostać zainicjowana podczas runtime przy użyciu JavaScript.
"bindEmail" to sprawdzi czy email jest dostępny czy nie. jeśli email istnieje to pokaże się Logout w przeciwnym wypadku pokaże się Login
<li *ngIf="bindEmail;then logout else login"></li>
<ng-template #logout><li><a routerLink="/logout">Logout</a></li></ng-template>
<ng-template #login><li><a routerLink="/login">Login</a></li></ng-template>
W Angular 4.0 składnia if..else
jest dość podobna do operatorów warunkowych w Javie.
W Javie używasz do tego celu "condition?stmnt1:stmnt2"
.
W Angular 4.0 używasz *ngIf="condition;then stmnt1 else stmnt2"
.