【发布时间】:2017-10-27 14:07:39
【问题描述】:
我只是在玩@ViewChild/@ContentChild,我很惊讶地发现@ViewChild 在指令内部不起作用并且对组件工作正常。但在指令中它不起作用。我尝试使用 AfterViewInit 钩子,所以生命周期钩子不是原因。这里还有其他问题,请在下面找到代码。
app.component.html
<div appMain >
<div #testContentDiv style="background-color: grey">
<p>This is the first p tag</p>
<p>This is the second p tag</p>
</div>
<div #testViewDiv style="background-color: yellow">
<p>This is the first p tag</p>
<p>This is the second p tag</p>
</div>
<app-test-child></app-test-child>
</div>
test-dir.ts --指令
import { Directive, ViewChild, ElementRef, OnInit, AfterViewInit, AfterContentInit, ContentChild } from '@angular/core';
@Directive({
selector: '[appMain]'
})
export class MainDirective implements OnInit, AfterContentInit, AfterViewInit {
constructor() { }
// tslint:disable-next-line:member-ordering
@ContentChild('testContentDiv') testContent: ElementRef;
@ViewChild('testViewDiv') testView: ElementRef;
ngOnInit() {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
// console.log(this.test.nativeElement);
}
ngAfterContentInit() {
//Called after ngOnInit when the component's or directive's content has been initialized.
//Add 'implements AfterContentInit' to the class.
console.log('Content Div: ngAfterContentInit: ' + this.testContent.nativeElement);
// console.log('View Div: ngAfterContentInit: ' + this.testView.nativeElement);
}
ngAfterViewInit() {
//Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
//Add 'implements AfterViewInit' to the class.
console.log('Content Div:ngAfterViewInit: ' + this.testContent.nativeElement);
console.log('View Div: ngAfterViewInit: ' + this.testView.nativeElement);
}
}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = "App works";
constructor() {
}
}
【问题讨论】:
-
我正在使用带有 Cli 的 Angular v4.1.3
-
我很惊讶地发现 @ViewChild 在指令中不起作用 - 指令没有视图/模板,您希望找到什么?
@ContentChild应该可以工作 -
ContentChild 确实有效。但是为什么不 ViewChild 呢?我没有尝试查看任何模板,而是尝试使用已为组件初始化的 ViewChild 引用元素
-
认为指令是母马元数据/标签...识别/帮助其他东西...只是为了避免混淆..
标签: angular angular2-directives