简体   繁体   English

Angular:如何使用ViewChild更改CSS

[英]Angular: how to change css using ViewChild

I would like to change a css style using ViewChild or Renderer2, but I am unable to. 我想使用ViewChild或Renderer2更改css样式,但是我做不到。 Do you have a code example? 你有代码示例吗?

Below is the code that does't work. 以下是无效的代码。

constructor(private renderer: Renderer2) {}

public onClick(){                
      this.renderer.setStyle('main-wrapper', 'color', 'blue');   
     }

The first argument needs to be the element. 第一个参数必须是元素。 For example, if your element has the id of main-wrapper, then you could do: 例如,如果您的元素具有main-wrapper的ID,则可以执行以下操作:

const element = document.getElemenetById('main-wrapper');
this.renderer.setStyle(element, "color", "blue");

Though, I'd recommend using ViewChild instead: 不过,我建议改用ViewChild:

<div #mainWrapperElement>
     ....
</div>

import { ViewChild } from '@angular/core';

@ViewChild('mainWrapperElement') myElement: HTMLElement;

then... 然后...

this.renderer.setStyle(this.myElement, "color", "blue");

On a side note, angular has really cool ways to manipulate styles that I would suggest looking into (ngStyle or style binding). 顺便说一句,angular有很多很酷的方式来处理我建议研究的样式(ngStyle或样式绑定)。

Try this: 尝试这个:

export class BypartSubBarComponent implements AfterViewInit {
@ViewChild('subbar', {static: false}) subbar: MatToolbar;
  constructor(
    private renderer: Renderer2) { }
  ngAfterViewInit() {
    this.renderer.setStyle(this.subbar._elementRef.nativeElement, 'backgroundColor', '#ff0000');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM