1

I am trying to create a simple directive in Angular 2 which highlights the content inside an html element.

Here is my code:

main.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from '@angular/core';
import {HighLightCmp} from "./highlight.component";

@Component({
    selector: 'app',
    template: `

    <div highlight>
        Highlight me.
    </div>
        `,
    directives: [HighLightCmp]
})
class AppCmp{

    constructor(){}
}

bootstrap(AppCmp);

highlight.component.ts

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

@Directive({
    selector: "[highlight]"
})
export class HighLightCmp implements OnInit{

    private color: "green";

    constructor(private _elRef:ElementRef,private _renderer:Renderer){}

    ngOnInit(){
        this._renderer.setElementStyle(this._elRef,"background-color",this.color);
    }
}

But I am getting the following exception while running

EXCEPTION: TypeError: Cannot set property 'background-color' of undefined

I re-produced the problem here on plunker

You can see the error message in the console. Any thoughts?

Thanks in anticipation.

1
  • Don't know if you saw my answer already. I added a few things. Commented Jun 16, 2016 at 6:51

1 Answer 1

2

some issues

This changed a while ago, maybe you find this in an outdated example. Since a while the Renderer methods need the nativeElement being passed instead of ElementRef:

this._renderer.setElementStyle(this._elRef.nativeElement, "background-color",this.color);

There is also an error in the variable definition

private color: "green";

should be

private color:string = "green";

alternative approach (preferred)

A better way would be to use @HostBinding() instead

@Directive({
    selector: "[highlight]"
})
export class HighLightCmp implements OnInit{

    @HostBinding('style.background-color')
    private color: "green";
}

@HostBinding() can also be combined with @Input() to be able to pass the value from the outside like [highlight]="red":

    @HostBinding('style.background-color')
    @Input()
    private color: "green";

The only downside of this approach is that the style properties (or attribute and class) names you want to bind to, need to be known at development time, while with your Renderer approach, they can be dynamic (for example passed in to an @Input()

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Gunter. I appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.