我正在学习angular,我正在尝试使用_renderer.setElementStyle设置背景颜色,但它不适用,有人可以帮助我吗
export class AppComponent {
constructor(private elementRef: ElementRef,
private render: Renderer) { }
@HostListener("mouseover") onmouseover() {
this.changeTextColor("red");
}
@HostListener("mouseleave") onmouseleave() {
this.changeTextColor("blue");
}
changeTextColor(color: string) {
this.render.setElementStyle(this.elementRef.nativeElement,"background-color",color);
}
}https://stackblitz.com/edit/angular-jsm9ii?file=src%2Fapp%2Fapp.component.ts
发布于 2019-02-01 20:29:19
默认情况下,组件元素具有内联显示样式。您应该使用css将其更改为块样式:
:host {
display: block;
}这将使stack正常工作。
另一方面,Renderer已弃用,在编写本文时,应该使用具有setStyle方法的Renderer2
另一方面,不应该使用渲染器来完成这样的任务。最重要的是,你不应该使用渲染器,除非你不能以其他方式访问元素。例如,如果它们是通过第三方库注入的。
我知道您正在尝试angular,但为了让它成为一个完整的答案,处理这个问题的最好方法是使用@HostBinding()和一个样式或类绑定。这仍然没有消除使其成为块元素的必要性。因此,将bgColor附加到components模板中的块元素可能会更好:
@HostBinding('style.backgroundColor')
bgColor: string = 'blue';
@HostListener("mouseover") onmouseover() {
this.bgColor = "red";
}
@HostListener("mouseleave") onmouseleave() {
this.bgColor = "blue";
}https://stackoverflow.com/questions/54479405
复制相似问题