75 lines
2.2 KiB
TypeScript
Raw Normal View History

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
2016-07-07 16:35:13 -07:00
import {Directive, DoCheck, ElementRef, Input, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer} from '@angular/core';
/**
* @ngModule CommonModule
*
* @whatItDoes Update an HTML element styles.
*
* @howToUse
* ```
* <some-element [ngStyle]="{'font-style': styleExp}">...</some-element>
*
* <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>
*
* <some-element [ngStyle]="objExp">...</some-element>
* ```
*
* @description
*
* The styles are updated according to the value of the expression evaluation:
* - keys are style names with an option `.<unit>` suffix (ie 'top.px', 'font-style.em'),
* - values are the values assigned to those properties (expressed in the given unit).
*
* @stable
*/
@Directive({selector: '[ngStyle]'})
export class NgStyle implements DoCheck {
2016-09-22 10:34:00 -07:00
private _ngStyle: {[key: string]: string};
private _differ: KeyValueDiffer;
constructor(
private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {}
2016-07-07 16:35:13 -07:00
@Input()
set ngStyle(v: {[key: string]: string}) {
this._ngStyle = v;
2016-09-08 19:25:25 -07:00
if (!this._differ && v) {
this._differ = this._differs.find(v).create(null);
}
}
ngDoCheck() {
2016-09-08 19:25:25 -07:00
if (this._differ) {
const changes = this._differ.diff(this._ngStyle);
if (changes) {
this._applyChanges(changes);
}
}
}
private _applyChanges(changes: any): void {
2016-09-08 19:25:25 -07:00
changes.forEachRemovedItem((record: KeyValueChangeRecord) => this._setStyle(record.key, null));
2016-02-11 17:01:17 -08:00
changes.forEachAddedItem(
2016-09-08 19:25:25 -07:00
(record: KeyValueChangeRecord) => this._setStyle(record.key, record.currentValue));
2016-02-11 17:01:17 -08:00
changes.forEachChangedItem(
2016-09-08 19:25:25 -07:00
(record: KeyValueChangeRecord) => this._setStyle(record.key, record.currentValue));
}
2016-09-08 19:25:25 -07:00
private _setStyle(nameAndUnit: string, value: string): void {
const [name, unit] = nameAndUnit.split('.');
value = value !== null && value !== void(0) && unit ? `${value}${unit}` : value;
2016-09-08 19:25:25 -07:00
this._renderer.setElementStyle(this._ngEl.nativeElement, name, value);
}
}