4

我正在尝试访问 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 不是函数

4

1 回答 1

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);
    }
}
于 2017-03-02T23:50:52.277 回答