【发布时间】:2017-10-15 12:45:27
【问题描述】:
我正在尝试从父指令访问子结构指令。
这就是我试图访问孩子的方式
@Directive({
selector: '[appChildStruralDirective]'
})
export class ChildStruralDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef, private renderer: Renderer) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
ngAfterViewInit(): void {
}
}
@Directive({
selector: '[appParentStruralDirective]'
})
export class ParentStruralDirective {
@ViewChild(ChildStruralDirective) viewChild: ChildStruralDirective;
@ContentChild(ChildStruralDirective) contentChild: ChildStruralDirective;
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef, private renderer: Renderer) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
ngAfterViewInit(): void {
console.log('ngAfterViewInit:viewChild', this.viewChild);
console.log('ngAfterViewInit:contentChild', this.contentChild);
}
ngAfterContentChecked(): void {
console.log('ngAfterContentChecked:viewChild', this.viewChild);
console.log('ngAfterContentChecked:contentChild', this.contentChild);
}
}
@Component({
selector: 'my-app',
template: `
<h1 *appParentStruralDirective>
<span *appChildStruralDirective>Hello world</span>
</h1>
`,
})
export class App {
constructor() {
}
}
我不确定为什么子指令不可访问。
我创建了一个 plunkr 来演示这个问题。
https://plnkr.co/edit/deQC6cY4oHuNdKbzsfhE?p=preview
请告诉我为什么这不起作用。
PS:我同时使用了 ViewChild 和 ContentChild(很可能是候选),因为我不确定这属于哪一个,因为它们是动态生成的元素。
【问题讨论】:
-
您可以注入一个服务,在该服务上注册子结构指令。
-
这违背了拥有 DI 的目的
-
AFAIK 这行不通。在github上创建问题github.com/angular/angular/issues
-
您不能注入
ParentStruralDirective,因为它不是 DI 树的一部分。您只能注入组件
标签: angular angular2-directives angular2-di