简体   繁体   English

带有 ng-template 的 Angular 内容子项不起作用

[英]Angular content child with ng-template doesn't work

I have the following directive:我有以下指令:

@Directive({
  selector: '[appTest]'
})
export class TestDirective {
  @ContentChild(ButtonComponent, { static: false }) button;
  constructor() { }

  ngAfterContentInit() {
    console.log(this.button);
  }

}

And I want to use it with <ng-template> :我想将它与<ng-template>一起使用:

<ng-template appTest>
  <app-button></app-button>
</ng-template>

But it doesn't work.但它不起作用。 I can't get a reference to the button.我无法获得对按钮的引用。 The log is undefined .日志undefined How can I make it work?我怎样才能让它工作?

You can't retrieve elements or directives that are in other components' templates, since a component's template is always a black box to its ancestors ContentChild您无法检索其他组件模板中的元素或指令,因为组件的模板始终是其祖先ContentChild的黑匣子

What you can do is using templateRef & viewContainer你可以做的是使用templateRef & viewContainer

You'll acquire the contents with a TemplateRef and access the view container through a ViewContainerRef.您将使用 TemplateRef 获取内容并通过 ViewContainerRef 访问视图容器。

@Directive({
  selector: '[appTest]'
})
export class TestDirective {

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

    var embeddedViewRef = viewContainer.createEmbeddedView(this.templateRef);

    for (var node of embeddedViewRef.rootNodes) {

      //Your button component
      console.log(node);
    }
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM