Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set attributes on an element in Angular 2?

Tags:

angular

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?

like image 757
zelda Avatar asked Feb 15 '17 23:02

zelda


People also ask

How to set attribute in Angular?

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.

How to bind data attribute in Angular?

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 (.)

What are attribute directive in Angular?

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.

What is attribute and property binding?

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.


2 Answers

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")

like image 130
Adam Avatar answered Oct 18 '22 15:10

Adam


You an use @HostBinding like

export class Checker {

  @HostBinding('attr.spellcheck')
  spellcheck:boolean = true;
like image 33
Günter Zöchbauer Avatar answered Oct 18 '22 16:10

Günter Zöchbauer