![](/img/trans.png)
[英]Accessing DOM element via nativeElement property of ElementRef is a bad practice in Angular?
[英]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.