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');
}
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.
ViewChild is used to select an element from component's template while ContentChild is used to select projected content.
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.
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.
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With