I am using ViewChild in Angular 2 to isolate an element. I can directly manipulate the styles but I cannot find documentation on if it is possible to change the elements style class.
This is sample code:
export class HomeComponent implements OnInit {
@ViewChild('slideBg') el:ElementRef;
ngAfterViewInit {
// style can be changed
this.el.nativeElement.style.background = 'red';
// does not work:
this.el.nativeElement.class = 'myCSSclass';
}
…
}
Looking to see if this is possible and how. Any help appreciated.
ViewChild is used to select an element from component's template while ContentChild is used to select projected content.
The @ViewChild decorator allows us to inject into a component class references to elements used inside its template, that's what we should use it for. Using @ViewChild we can easily inject components, directives or plain DOM elements.
ViewChildlink Property 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.
Seems you are looking for className
property:
this.el.nativeElement.className = 'myCSSclass';
Element.className
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