Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: how to change css using ViewChild

I would like to change a css style using ViewChild or Renderer2, but I am unable to. 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');   
     }
like image 304
Gelso77 Avatar asked Sep 27 '18 16:09

Gelso77


People also ask

How does ViewChild work in Angular?

ViewChildlinkProperty decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

What is the difference between ViewChild () and ContentChild ()?

ViewChild is used to select an element from component's template while ContentChild is used to select projected content.

What is possible with ViewChild?

ViewChild makes it possible to access native DOM elements that have a template reference variable. Let's say you have an <input> in the template with the #someInput reference variable. Replace the contents of app.component.html with the following: app.component.html.

What is difference between ViewChild and ViewChildren?

Working with @ViewChildren is similar to @ViewChild, but the difference between the two is @ViewChildren provides a list of element references rather than returning a single reference. It is used to reference multiple elements. We can then iterate the list of the element referenced by the variable.


1 Answers

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');
  }
}
like image 130
Post Impatica Avatar answered Sep 28 '22 00:09

Post Impatica