forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathng_style.ts
More file actions
65 lines (59 loc) · 2.02 KB
/
ng_style.ts
File metadata and controls
65 lines (59 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import {DoCheck} from 'angular2/lifecycle_hooks';
import {
KeyValueDiffer,
KeyValueDiffers,
} from 'angular2/src/core/change_detection';
import {ElementRef} from 'angular2/src/core/compiler';
import {Directive} from 'angular2/src/core/metadata';
import {Renderer} from 'angular2/src/core/render';
import {isPresent, isBlank, print} from 'angular2/src/core/facade/lang';
/**
* Adds or removes styles based on an {expression}.
*
* When the expression assigned to `ng-style` evaluates to an object, the corresponding element
* styles are updated. Style names to update are taken from the object keys and values - from the
* corresponding object values.
*
* # Example:
*
* ```
* <div [ng-style]="{'text-align': alignExp}"></div>
* ```
*
* In the above example the `text-align` style will be updated based on the `alignExp` value
* changes.
*
* # Syntax
*
* - `<div [ng-style]="{'text-align': alignExp}"></div>`
* - `<div [ng-style]="styleExp"></div>`
*/
@Directive({selector: '[ng-style]', properties: ['rawStyle: ng-style']})
export class NgStyle implements DoCheck {
_rawStyle;
_differ: KeyValueDiffer;
constructor(private _differs: KeyValueDiffers, private _ngEl: ElementRef,
private _renderer: Renderer) {}
set rawStyle(v) {
this._rawStyle = v;
if (isBlank(this._differ) && isPresent(v)) {
this._differ = this._differs.find(this._rawStyle).create(null);
}
}
doCheck() {
if (isPresent(this._differ)) {
var changes = this._differ.diff(this._rawStyle);
if (isPresent(changes)) {
this._applyChanges(changes);
}
}
}
private _applyChanges(changes: any): void {
changes.forEachAddedItem((record) => { this._setStyle(record.key, record.currentValue); });
changes.forEachChangedItem((record) => { this._setStyle(record.key, record.currentValue); });
changes.forEachRemovedItem((record) => { this._setStyle(record.key, null); });
}
private _setStyle(name: string, val: string): void {
this._renderer.setElementStyle(this._ngEl, name, val);
}
}