getting 'nativeElement.querySelector is not a function' exception in Angular2

mohsen picture mohsen · Feb 22, 2017 · Viewed 12k times · Source

I'm trying to access a div in Angular2 like below:

import { Component, ViewChild, ElementRef, AfterContentInit } from '@angular/core';

@Component({
    selector: 'main',
    template: `
    <div  #target class="parent">
        <div class="child">
        </div>
    </div>
  `
})

export class MainComponent implements AfterContentInit {
    @ViewChild('target') elementRef: ElementRef;

    ngAfterContentInit(): void {
        var child = this.elementRef.nativeElement.querySelector('div');
        console.log(child);
    }
}

but I get the following exception:

Exception: Call to Node module failed with error: TypeError: this.elementRef.nativeElement.querySelector is not a function

Answer

William Lohan picture William Lohan · Mar 3, 2017

That template uses angular2-universal for server-side rendering. https://github.com/angular/universal#universal-gotchas

Try:

import { Component, AfterContentInit, ViewChild, ElementRef, Renderer } from '@angular/core';

@Component({
    selector: 'main',
    template: `
    <div  #target class="parent">
        <div class="child">
        </div>
    </div>
`
})
export class MainComponent implements AfterContentInit {
    @ViewChild('target') elementRef: ElementRef;

    constructor(private renderer: Renderer) {}

    ngAfterContentInit(): void {
        var child = this.renderer.invokeElementMethod(this.elementRef.nativeElement, 'querySelector', ['div']);
        console.log(child);
    }
}