我正在玩@ ViewChild / @ ContentChild,我很惊讶地看到@ViewChild在指令中没有工作,并且对于component.But在指令中运行正常。我尝试使用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() {
}
}
答案 0 :(得分:3)
Angular中有三种指令:
组件 - 带有模板的指令。
结构指令 - 通过添加和删除DOM元素来更改DOM布局。
属性指令 - 更改元素,组件或其他指令的外观或行为。
因此,根据定义,组件是唯一带有template
的指令,因此您只能为组件找到@ViewChild
。
详细了解here。
希望这会有所帮助!!