首页 > 解决方案 > 嵌套 Angular 结构指令的 ContentChild 未定义

问题描述

我有一个结构指令 A 嵌套在另一个结构指令 B 中。现在我想访问 A 内部的 B 以使用它的 templateRef。

我尝试使用 ContentChild,但它始终未定义。有人可以告诉我必须改变什么才能获得访问权限吗?

我在 StackBlitz 中重新创建了我的星座:https ://stackblitz.com/edit/angular-b697ct?file=src%2Fapp%2Fhello.component.ts

指令定义:


@Directive({selector: '[testChild]'})
export class B {

}

@Directive({selector: '[testParent]'})
export class A {
  @ContentChild(B, {static: false}) contentTemplate: B;

  constructor(public viewContainer: ViewContainerRef, public templateRef: TemplateRef<any>) {
  }

  ngAfterViewInit() {
    console.log(this.contentTemplate); // logs undefined
  }
}

@Directive({selector: '[tstOutlet]'})
export class TestOutlet {
  constructor(public viewContainer: ViewContainerRef) {
  }
}

@Component({
  selector: 'tst',
  template: `<ng-container tstOutlet></ng-container>`,
})
export class HelloComponent implements AfterViewInit {
  @ContentChildren(A) parents: QueryList<A>;

  @ViewChild(TestOutlet, {static: true}) outlet: TestOutlet;

  ngAfterViewInit() {
    this.parents.toArray().forEach((parent: A) => {
      this.outlet.viewContainer.createEmbeddedView(parent.templateRef);
    });
  }
}

模板定义:

<tst>
  <ng-container *testParent>
    <span *testChild>Test</span>
  </ng-container>

  <ng-container *testParent>
    <span *testChild>Second Test</span>
  </ng-container>
</tst>

标签: javascriptangularangular2-templateangular2-directives

解决方案


推荐阅读