Search code examples
angularrenderer

'classList' is undefined when using setElementClass in angular2


here is my code...

constructor(private loginService: LoginService, 
            private router: Router, 
            private renderer: Renderer) { }

@ViewChild('element') private element: ElementRef;
this.renderer.setElementClass(this.element, 'shake', false);

it causes 'Cannot read property 'classList' of undefined'

if I change this way...

this.renderer.setElementClass(this.element.nativeElement, 'shake', false);

it causes 'Cannot read property 'nativeElement' of undefined'

how can I set element's class again?


Solution

  • Here is how you can get the Dom elememt:

    component.html

    <div #myDiv></div>
    

    component.ts

    @ViewChild('myDiv') private myDiv: ElementRef;
    
    ngAfterViewInit () {
        this.renderer.setElementClass(this.myDiv.nativeElement, 'shake', true); } }
    }
    

    Here is a working plunk: DEMO