ngStyle VS Renderer2 ? What should I use?

后端 未结 1 1723
春和景丽
春和景丽 2021-01-20 14:48

I\'m using Angular 5.2.9.

I was wondering when should I use Renderer2 over ngStyle ? Which is the best solution ?

1:

FOO BAR
1条回答
  •  旧巷少年郎
    2021-01-20 15:10

    Both ngStyle and renderer.setStyle are used to dynamically style a component

    But renderer.setStyle looks to take precedence over [ngStyle] even if ngStyle looks to be a type of embedded style.

    Demo example:

    https://stackblitz.com/edit/angular-jtdk4z?file=src%2Fapp%2Fapp.component.html

    When looking to the internal implementation of ngStyle:

    https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_style.ts

    it looks like it itself is implemented using renderer.setStyle

    @Directive({selector: '[ngStyle]'})
    export class NgStyle implements DoCheck {
      private _ngStyle: {[key: string]: string};
      private _differ: KeyValueDiffer;
    
      constructor(
          private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer2) {}
    
      @Input()
      set ngStyle(v: {[key: string]: string}) {
        this._ngStyle = v;
        if (!this._differ && v) {
          this._differ = this._differs.find(v).create();
        }
      }
    
      ngDoCheck() {
        if (this._differ) {
          const changes = this._differ.diff(this._ngStyle);
          if (changes) {
            this._applyChanges(changes);
          }
        }
      }
    
      private _applyChanges(changes: KeyValueChanges): void {
        changes.forEachRemovedItem((record) => this._setStyle(record.key, null));
        changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue));
        changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue));
      }
    
      private _setStyle(nameAndUnit: string, value: string|number|null|undefined): void {
        const [name, unit] = nameAndUnit.split('.');
        value = value != null && unit ? `${value}${unit}` : value;
    
        if (value != null) {
          this._renderer.setStyle(this._ngEl.nativeElement, name, value as string);
        } else {
          this._renderer.removeStyle(this._ngEl.nativeElement, name);
        }
    }
    

    0 讨论(0)
提交回复
热议问题