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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…