angular - renderer.setElementStyle “Cannot set property ' 背景颜色'

标签 angular

我正在学习 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/

相关文章:

javascript - Angular 2 - 如何使用新的 Angular 2.0.0-rc.1 路由器

angular - 未捕获的类型错误 : StaticInjectorError(Platform: core)[t]: Cannot set property '_injector' of undefined

jquery - Angular 有条件地改变元素的背景颜色

Angular 2 ng2-智能表:issue while catch the data from custom button event

forms - 选择地址时, Angular 形式不验证

Angular 2 *ngFor 仅支持在内联模板中一次添加 10 个元素

angular - 如何回滚 AngularFire2 4.0,回到 AngularFire 2 2.0?

Angular PUT 请求在 SSL 上被禁止

Angular trackBy 返回 *ngFor 中的索引 vs item id

angular - 没有函数 (){} 的提供者! Angular 4