If you want to achieve that, you have two options: the *ngIf
directive or the hidden
property.
Take note of the distinction:
*ngIf
removes and recreates the element:
When the expression assigned to ngIf evaluates to false, the
element is removed from the DOM; otherwise, a clone of the element is
reinserted into the DOM.
hidden
hides the element using display: none
According to angular's documentation:
The show/hide technique is probably fine for small element trees. We
should be wary when hiding large trees; NgIf may be the safer choice.
Always measure before leaping to conclusions.
Take a look at the example below:
@Component({
selector: 'my-app',
template: `
<b>Using *ngIf:</b>
<div *ngIf="!isOn">Light Off</div>
<div *ngIf="isOn">Light On</div>
<br />
<b>Using [hidden]:</b>
<div [hidden]="isOn">Light Off</div>
<div [hidden]="!isOn">Light On</div>
<br />
<button (click)="setState()">{{ getButtonText() }}</button>
`
})
export class AppComponent {
private isOn: boolean = false;
getButtonText(): string {
return `Switch ${ this.isOn ? 'Off' : 'On' }`;
}
setState(): void {
this.isOn = !this.isOn;
}
}
Plunker: http://plnkr.co/edit/7b1eWgSHiM1QV6vDUAB0
For more information on [hidden]
, I recommend reading this article:
I hope this explanation helps.