/** * @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 */ import {Directive, DoCheck, ElementRef, Input, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer} from '@angular/core'; /** * @ngModule CommonModule * * @whatItDoes Update an HTML element styles. * * @howToUse * ``` * ... * * ... * * ... * ``` * * @description * * The styles are updated according to the value of the expression evaluation: * - keys are style names with an option `.` 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 { /** @internal */ _ngStyle: {[key: string]: string}; /** @internal */ _differ: KeyValueDiffer; constructor( private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {} @Input() set ngStyle(v: {[key: string]: string}) { this._ngStyle = v; if (!this._differ && v) { this._differ = this._differs.find(v).create(null); } } ngDoCheck() { if (this._differ) { const changes = this._differ.diff(this._ngStyle); if (changes) { this._applyChanges(changes); } } } private _applyChanges(changes: any): void { changes.forEachRemovedItem((record: KeyValueChangeRecord) => this._setStyle(record.key, null)); changes.forEachAddedItem( (record: KeyValueChangeRecord) => this._setStyle(record.key, record.currentValue)); changes.forEachChangedItem( (record: KeyValueChangeRecord) => this._setStyle(record.key, record.currentValue)); } private _setStyle(nameAndUnit: string, value: string): void { const [name, unit] = nameAndUnit.split('.'); value = value !== null && value !== void(0) && unit ? `${value}${unit}` : value; this._renderer.setElementStyle(this._ngEl.nativeElement, name, value); } }