【发布时间】:2020-08-02 06:11:17
【问题描述】:
希望有人能启发我。
问题
我需要获取对放置在内部组件中的指令的引用。 我正在使用 @ViewChild 定位 Directive 类,使用 {static:true} 因为它不必等待状态更改并稍后在用户单击按钮时在生命周期中使用它。
@ViewChild(DirectiveClass, {static:true}) childRef : DirectiveClass;
预期
事件发生时在 childRef 实例变量中有指令引用。
实际
childRef 是undefined
我对类似问题进行了研究,似乎都是因为 ref 在 *ngIf 内,应该是 {static: false};或者因为 ref 打算在它被获取之前使用(在 ngAfterViewInit 钩子之前)。情况并非如此,这种情况相当简单,但又不会出错! :/
复制
情况
所以,我得到了两个组件和一个指令。让我们称它们为 ParentComponent 和 SonComponent。子组件中应用了指令,所以我们称它为 SonDirective。
基本上就是这样的结构。
<app-parent>
<app-son> </app-son> //<- Directive inside
</app-parent>
代码
//parent.component.ts
@Component({
selector: 'app-parent',
template: `
<div>
<h2> parent </h2>
<app-son></app-son>
</div>
`,
})
export class AppParentComponent implements AfterViewInit{
@ViewChild(AppSonDirective,{static: true}) childRef : AppSonDirective;
constructor() {}
ngAfterViewInit() {
console.log("childRef:",this.childRef)
}
}
// son.component.ts
@Component({
selector: 'app-son',
template: `
<div appSonDirective>
<p> son <p>
</div>
`,
})
export class AppSonComponent {
constructor() {}
}
//son.directive.ts
@Directive({
selector: '[appSonDirective]'
})
export class AppSonDirective {
constructor(){}
}
注意: 如果我将视图子引用移动到子组件,则可以访问它。问题似乎出在父组件(?)
无论如何...here 是复制代码(它有一些日志可以知道发生了什么)
任何想法都会有所帮助。
提前致谢! :)
【问题讨论】:
标签: javascript angular typescript viewchild