2015-11-18 15:55:43 -08:00
|
|
|
import {Directive, ViewContainerRef, TemplateRef} from 'angular2/core';
|
2015-11-06 17:34:07 -08:00
|
|
|
import {isBlank} from 'angular2/src/facade/lang';
|
2014-12-17 10:01:08 +01:00
|
|
|
|
2015-03-31 22:47:11 +00:00
|
|
|
/**
|
2015-04-10 11:15:01 -07:00
|
|
|
* Removes or recreates a portion of the DOM tree based on an {expression}.
|
|
|
|
*
|
2015-11-23 16:02:19 -08:00
|
|
|
* If the expression assigned to `ngIf` evaluates to a false value then the element
|
2015-06-02 08:55:58 -07:00
|
|
|
* is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
|
2015-04-06 11:47:38 +02:00
|
|
|
*
|
2015-09-17 15:28:11 -07:00
|
|
|
* ### Example ([live demo](http://plnkr.co/edit/fe0kgemFBtmQOY31b4tw?p=preview)):
|
2015-04-06 11:47:38 +02:00
|
|
|
*
|
|
|
|
* ```
|
2015-11-23 16:02:19 -08:00
|
|
|
* <div *ngIf="errorCount > 0" class="error">
|
2015-05-20 17:19:46 -07:00
|
|
|
* <!-- Error message displayed when the errorCount property on the current context is greater
|
|
|
|
* than 0. -->
|
2015-04-06 11:47:38 +02:00
|
|
|
* {{errorCount}} errors detected
|
|
|
|
* </div>
|
|
|
|
* ```
|
|
|
|
*
|
2015-11-17 09:41:31 -08:00
|
|
|
* ### Syntax
|
2015-04-06 11:47:38 +02:00
|
|
|
*
|
2015-11-23 16:02:19 -08:00
|
|
|
* - `<div *ngIf="condition">...</div>`
|
|
|
|
* - `<div template="ngIf condition">...</div>`
|
|
|
|
* - `<template [ngIf]="condition"><div>...</div></template>`
|
2015-03-31 22:47:11 +00:00
|
|
|
*/
|
2015-11-23 16:02:19 -08:00
|
|
|
@Directive({selector: '[ngIf]', inputs: ['ngIf']})
|
2015-05-11 15:58:59 -07:00
|
|
|
export class NgIf {
|
2015-08-13 13:18:41 -07:00
|
|
|
private _prevCondition: boolean = null;
|
2014-12-17 10:01:08 +01:00
|
|
|
|
2015-08-13 13:18:41 -07:00
|
|
|
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef) {}
|
2014-12-17 10:01:08 +01:00
|
|
|
|
2015-05-11 15:58:59 -07:00
|
|
|
set ngIf(newCondition /* boolean */) {
|
2015-08-13 13:18:41 -07:00
|
|
|
if (newCondition && (isBlank(this._prevCondition) || !this._prevCondition)) {
|
|
|
|
this._prevCondition = true;
|
|
|
|
this._viewContainer.createEmbeddedView(this._templateRef);
|
|
|
|
} else if (!newCondition && (isBlank(this._prevCondition) || this._prevCondition)) {
|
|
|
|
this._prevCondition = false;
|
|
|
|
this._viewContainer.clear();
|
2014-12-17 10:01:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|