繁体   English   中英

在Angular2中使用nativeElement访问DOM有哪些好的替代方法?

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

以下面的代码为例,它们是使用nativeElement访问DOM的好方法

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);
     }
}

这是一个让你更容易测试的Plunker

由于不鼓励通过nativeElement直接访问DOM, nativeElement您有三个选项

  • 使用host属性(这将立即设置颜色)
@Directive({
    host:{
        '(mouseenter)' : ' mouseEnter()',
        '[style.background-color]' : 'myColor'
    }
})

mouseEnter(){
    this.myColor = 'blue';
}
  • 使用@HostBinding (这种情况会立即设置颜色)
@HostBinding('style.background-color') get color {
    return this.myColor;
}

mouseEnter(){
    this.myColor = 'blue';
}
  • 使用Renderer (使用此代替nativeElement.style = 'value'
constructor(public renderer: Renderer, public element: ElementRef) {}

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

请注意, host@HostBinding是等效的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM