Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change element class on ViewChild in Angular 2

Tags:

angular

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.

like image 283
lukemcd Avatar asked Feb 24 '17 17:02

lukemcd


People also ask

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 the use of annotation @ViewChild?

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.

What does ViewChild do in Angular?

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.


1 Answers

Seems you are looking for className property:

this.el.nativeElement.className = 'myCSSclass';

Element.className

like image 58
yurzui Avatar answered Oct 19 '22 16:10

yurzui