Files
angular-docs-cn/modules/angular2/src/directives/if.js
T

53 lines
1.5 KiB
JavaScript
Raw Normal View History

import {Viewport} from 'angular2/src/core/annotations/annotations';
import {ViewContainerRef} from 'angular2/src/core/compiler/view_container_ref';
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}.
*
* If the expression assigned to `if` evaluates to a false value then the element is removed from the
2015-04-06 11:47:38 +02:00
* DOM, otherwise a clone of the element is reinserted into the DOM.
*
* # Example:
*
* ```
* <div *if="errorCount > 0" class="error">
* <!-- Error message displayed when the errorCount property on the current context is greater than 0. -->
* {{errorCount}} errors detected
* </div>
* ```
*
* # Syntax
*
* - `<div *if="condition">...</div>`
* - `<div template="if condition">...</div>`
* - `<template [if]="condition"><div>...</div></template>`
*
* @exportedAs angular2/directives
2015-03-31 22:47:11 +00:00
*/
@Viewport({
selector: '[if]',
properties: {
'condition': 'if'
2014-12-17 10:01:08 +01:00
}
})
export class If {
viewContainer: ViewContainerRef;
2014-12-17 10:01:08 +01:00
prevCondition: boolean;
constructor(viewContainer: ViewContainerRef) {
this.viewContainer = viewContainer;
2014-12-17 10:01:08 +01:00
this.prevCondition = null;
}
2015-04-19 14:47:02 -07:00
set condition(newCondition /* boolean */) {
2014-12-17 10:01:08 +01:00
if (newCondition && (isBlank(this.prevCondition) || !this.prevCondition)) {
this.prevCondition = true;
this.viewContainer.create();
2014-12-17 10:01:08 +01:00
} else if (!newCondition && (isBlank(this.prevCondition) || this.prevCondition)) {
this.prevCondition = false;
this.viewContainer.clear();
2014-12-17 10:01:08 +01:00
}
}
}