【发布时间】:2017-05-18 19:49:08
【问题描述】:
我一直在尝试访问我通过使用@ViewChild(CustomDirective) 或@ContentChild(CustomDirective) 分别在我的ngAfterViewInit 或ngAfterContentInit 函数中首次使用set 变量来访问我在元素上应用的自定义指令。
但是,他们都没有工作。 一开始我以为是我从网络服务器加载了一些内容,但即使设置了静态变量,它也不起作用。
这是我所拥有的:
@Directive({
selector: '[det-insert]',
})
export class DetailedDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
和
... (importing + component stuff)
export class DetailedView implements AfterViewInit {
@ViewChild(DetailedDirective) detView : DetailedDirective;
constructor(...)
ngAfterViewInit(){
alert(detView);
}
}
还有模板:
<ng-template det-insert></ng-template>
但是,警报返回undefined。
我不知道为什么。有任何想法吗?我已经查看了stackoverflow,但我的模板也没有被*ngIf 阻碍,我也没有在正确的“AfterXInit”函数之前开始使用我的查询指令。我已经尝试分别为 ViewContent 和 AfterContentInit 切换 ViewChild 和 AfterViewInit,但无济于事。
【问题讨论】:
-
<ng-template>未添加到 DOM,因此无法找到DetailedDirective。如果您使用<div det-insert>,它将起作用 -
@GünterZöchbauer 感谢您的回答!不幸的是,我试过了,但它仍然不起作用......(仍然输出未定义。此外,我的代码与上面的代码没有任何不同 - 我将所有差异都注释掉了。)(我再次尝试使用 ViewChild 和 ContentChild )
-
您是否将
DetailedDirective添加到您的模块的declarations: [] -
@GünterZöchbauer ...哦,我的上帝。我没有。我很抱歉像这样浪费你的时间......不过非常感谢你!想将其添加为“官方”答案吗?也许有一天有人会像我一样忘记在声明数组中添加指令并偶然发现这个线程......
标签: javascript angular initialization angular-directive