5

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

Micho
  • 3,929
  • 13
  • 37
  • 40
mohsen
  • 187
  • 1
  • 3
  • 12
  • That is strange the `ElementRef.nativeElement` is type `any`. What version of angular are you using or what dose your `package.json` look like? – Wilhelmina Lohan Feb 23 '17 at 00:16
  • i'm using angular 2.0.0. shouldn't work with this version? – mohsen Feb 26 '17 at 22:15
  • It should work an it works here https://plnkr.co/edit/fRsQot7KtIAUGSIIZdKA – Wilhelmina Lohan Feb 27 '17 at 17:30
  • yes, it should work but it doesn't. i also upgrade my project to Angular 2.4.5 but still the same result. i can't understand why. – mohsen Feb 28 '17 at 23:46
  • Can you post the full code, with it not working somewhere? – Wilhelmina Lohan Mar 01 '17 at 00:00
  • i'm using http://www.telerik.com/blogs/cooking-with-aspnet-core-and-angular-2 template for my project which has the issue. but when i use plnkr is working fine. also if i use a simple angular2 project without this template is working fine as well – mohsen Mar 01 '17 at 23:04

1 Answers1

3

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

Try:

import { Component, AfterContentInit, ViewChild, ElementRef } 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.elementRef.nativeElement as any).querySelector.apply(this.elementRef.nativeElement, ['div']);
        console.log(child);
    }
}

https://angular.io/guide/migration-renderer

rofrol
  • 14,438
  • 7
  • 79
  • 77
Wilhelmina Lohan
  • 2,803
  • 2
  • 29
  • 58