使用 ViewChild / ContentChild 访问自定义指令

Access custom directive with ViewChild / ContentChild

我一直在尝试使用 @ViewChild(CustomDirective)@ContentChild(CustomDirective) 访问我在元素上应用的自定义指令,分别是在我的 ngAfterViewInit 中第一次使用 set 变量或 ngAfterContentInit 函数。

然而,它们都不起作用。 起初,我以为是我从网络服务器加载了一些内容,但是即使设置了静态变量,它也不起作用。

这是我的:

@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>

但是,警报 returns undefined.

我不知道为什么。有任何想法吗?我已经查看了 Whosebug,但我的模板既没有被 *ngIf 阻碍,也没有在正确的 "AfterXInit" 函数之前开始使用我查询的指令。我已经尝试分别为 ViewContent 和 AfterContentInit 切换 ViewChild 和 AfterViewInit,但无济于事。

将 DetailedDirective 添加到声明中:模块的 []

<ng-template> 未添加到 DOM,因此无法找到 DetailedDirective。如果你使用 <div det-insert> 它将工作

我自己 运行 遇到过类似的问题。我为各种警报创建了一个单独的模块 directives/components。我的警报指令是在该警报模块中定义和声明的。我试图在我的应用程序模块中使用该指令,为了让这个相同的示例工作,您需要指定警报模块 exports: [AppLevelAlertDirective].

您仍然可以使用 <ng-template yourDirective></ng-template>,尽管它不会在以后的 DOM 中显示。这是在呈现 DOM 之前捕获的。请参阅 https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html#!#loading-components