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?
Attribute binding syntax resembles property binding, but instead of an element property between brackets, you precede the name of the attribute with the prefix attr , followed by a dot. Then, you set the attribute value with an expression that resolves to a string.
We simply use attribute binding to add and set a value for a data attribute. According to Angular docs: Attribute binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix attr, followed by a dot (.)
Angular attribute directives are a number of built-in directives that we can add to our HTML elements that give them a dynamic behavior. In summary, an attribute directive changes the appearance or behavior of a DOM element.
Attribute binding syntax is like property binding. In property binding, we only specify the element between brackets. But in the case of attribute binding, it starts with the prefix attar, followed by a dot (.), and the name of the attribute.
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")
You an use @HostBinding
like
export class Checker {
@HostBinding('attr.spellcheck')
spellcheck:boolean = true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With