我想从父指令访问子结构指令。无法从父结构指令访问子结构指令
这是我正在尝试访问孩子
@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上创建问题https://github.com/angular/angular/issues – yurzui