我正在学习 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
最佳答案
默认情况下,组件元素具有内联显示样式。您应该使用 css 将其更改为 block 样式:
:host {
display: block;
}
这将使stack工作。
另一方面,Renderer
已弃用,在撰写本文时,应使用 Renderer2
,其中有 setStyle 方法
另一方面,不应该使用渲染器来完成这样的任务。主要是,您永远不应该使用渲染器,除非您以某种方式无法访问元素。例如,如果它们是通过第三方库注入(inject)的。
我知道您正在尝试 Angular ,但只是为了使其成为完整的答案,处理此问题的最佳方法是使用 @HostBinding()
以及样式或类绑定(bind)。这仍然没有消除使其成为 block 元素的必要性。因此,也许最好将 bgColor
附加到组件模板内的 block 元素:
@HostBinding('style.backgroundColor')
bgColor: string = 'blue';
@HostListener("mouseover") onmouseover() {
this.bgColor = "red";
}
@HostListener("mouseleave") onmouseleave() {
this.bgColor = "blue";
}
关于angular - renderer.setElementStyle “Cannot set property ' 背景颜色',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479405/