Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some good alternatives to accessing the DOM using nativeElement in Angular2?

Tags:

angular

Taking as an example the following code, which are good alternatives to accessing the DOM using nativeElement

import {Component, Directive, Input, ElementRef} from 'angular2/core';

@Directive({
    selector: '[myDR]',
    host:{
        '(mouseenter)' : ' mouseEnter()'
    }
})

export class MyDi {

    @Input () myColor: string;

    constructor(private el:ElementRef) {

    }

    mouseEnter(){

        this.el.nativeElement.style.backgroundColor = this.myColor;

        console.log(this.myColor);
     }
}

This is a Plunker for you test more easy.

like image 545
Angel Angel Avatar asked Oct 30 '25 03:10

Angel Angel


1 Answers

Since accessing directly to DOM through nativeElement is discouraged you have three options

  • Using host property (this will set the color immediatly)
@Directive({
    host:{
        '(mouseenter)' : ' mouseEnter()',
        '[style.background-color]' : 'myColor'
    }
})

mouseEnter(){
    this.myColor = 'blue';
}
  • Using @HostBinding (this case will set the color immediatly)
@HostBinding('style.background-color') get color {
    return this.myColor;
}

mouseEnter(){
    this.myColor = 'blue';
}
  • Using Renderer (use this instead of nativeElement.style = 'value')
constructor(public renderer: Renderer, public element: ElementRef) {}

mouseEnter(){
  this.renderer.setElementStyle(this.element.nativeElement, 'background-color', this.myColor);
}

Note that host and @HostBinding are equivalent.

like image 60
Eric Martinez Avatar answered Nov 01 '25 19:11

Eric Martinez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!