0
votes

This is my component metadata:

@Component({
   moduleId: module.id,
   selector: 'si-attribute-directive',
   template: `
      <div myHighlight [customColor]="'red'">Highlight Me..</div>
      <br>
      <div myHighlight>Highlight Me Too..</div>
   `,
   directives: [MyHighlightDirective]
})

And this is my directive:

import { Directive, ElementRef, OnInit, Renderer, Input } from '@angular/core';

@Directive({
    selector: '[myHighlight]'
})
export class MyHighlightDirective implements OnInit {
   private _defaultColor : string = "green";
   @Input() customColor:string;
   constructor(private _elRef:ElementRef, private _renderer:Renderer) { }

   ngOnInit():any {
       this._renderer.setElementStyle(this._elRef, 'background-color', this.customColor || this._defaultColor);
   }
}

It's getting the error: "Cannot set property 'background-color' of undefined".

1
By the way, this line is working. this._elRef.nativeElement.style.backgroundColor = this.customColor || this._defaultColor; - H. Jabi
@#$#! Stop usign underscore for private properties! :) angular.io/styleguide#03-04 - Lyubimov Roman
Tried it. Doesn't work. - H. Jabi

1 Answers

7
votes

The problem is that you pass not native element. Try this:

this._renderer.setElementStyle(this._elRef.nativeElement, 'background-color', this.customColor || this._defaultColor);