11

I have a simple Directive as follows:

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

@Directive({
    selector: "[Checker]"
})
export class Checker {

    constructor(private e: ElementRef) {

    }

    OnInit() {
        this.e.nativeElement.setAttribute("spellcheck", "true");
    }

    keyFunc(event: KeyboardEvent) {
        if (event.keyCode == 74) {
            //more functionality
        }
    }

}

So, whenever I add this directive selector to any tag, I set the spellcheck attribute to true.

How can I set this attribute in an Angular2 way, i.e. what is the alternative Angular way to do this?

3 Answers 3

14

The 'Angular 2' way would be to use Renderer.

this.renderer.setElementAttribute(e.nativeElement, "spellcheck", "true");

Edit:

As PeterS notes in the comments below, renderer has been deprecated in favour of renderer2, so the new command would be:

this.renderer2.setAttribute(e.nativeElement, "spellcheck", "true")

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

5 Comments

Can I do it using @HostBinding() by any chance?
Yet to try this, but the link was broken so: angular.io/api/core/Renderer#setElementProperty
Thanks, @theSiberman. I updated the answer to use your new link.
Adam: Is there a way to set an @Input property to the host using renderer2 ? set [(color)] property to the Host element.
Note in angular 5 it is now setAttribute using renderer 2: this.renderer2.setAttribute(element, 'name', data)
12

You an use @HostBinding like

export class Checker {

  @HostBinding('attr.spellcheck')
  spellcheck:boolean = true;

Comments

6

You can simply declare the host property in the @Directive as follows:

@Directive({
    selector: "[Checker]",
    host: { "spellcheck":"true" }
})

And obviously you can remove the setAttribute() which you are using in the ngOnInit().

7 Comments

It would actually need to be "attr.spellcheck" : "true", and it's just the alternative syntax to @HostBinding(). Everything you can do with Angular decorators, @Input(), @Output(), @ViewChild(), @HostListener(), ..., can be done with host: as well.
@GünterZöchbauer I actually tried without attr, and it is working too. I am not sure which is the right way. I didn't try it with attr.spellcheck though.
If you bind to a components input or DOM elements property, then attr. is not required, otherwise attr. is required.
@GünterZöchbauer got it :)
Actually you were right. What I said is true for bindings in view like [attr.spellcheck]="true" and in @HostBinding('attr.spellcheck') sp = true;, but in host: {"spellcheck":"true"} attr. is not required. plnkr.co/edit/RyCb9Cs4g5J6fociXfKl?p=preview
|

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.