我正在尝试访问Angular2中的div,如下所示:
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);
}
}
但我得到以下例外:
异常:调用节点模块失败,错误:TypeError: this.elementRef.nativeElement.querySelector不是函数
答案 0 :(得分:2)
该模板使用angular2-universal
进行服务器端呈现。
https://github.com/angular/universal#universal-gotchas
尝试:
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);
}
}