【问题标题】:Angular pass template reference using ng-content使用 ng-content 的角度传递模板参考
【发布时间】:2020-02-21 07:37:12
【问题描述】:

我想将ng-template 作为嵌套在子元素中的ng-content 传递

app-component.html

<app-parent>
  <ng-template appTemplateRetrieval>
    <div>this should be passed to grand child</div>
  </ng-template>
</app-parent>

父组件.html

<app-child>
  {{directivesTemplate}}
</app-child>

父组件.ts

 @ContentChild(TemplateRetrievalDirective, {static: false}) tplRetDir: TemplateRetrievalDirective;

  get directivesTemplate(): TemplateRef<any> {
    return this.tplRetDir && this.tplRetDir.template;
  }

指令

export class TemplateRetrievalDirective {

  constructor(public template: TemplateRef<any>) { }

}

子组件.ts

@ContentChild(TemplateRef, {static: true}) contentTpl: TemplateRef<any>;

  ngAfterContentInit() {
    console.log(this.contentTpl) // logs to console: undefined
  }

stackblitz:https://stackblitz.com/edit/angular-cuipde

我希望TemplateRef 向下传递两个级别:app-component > parent > child

【问题讨论】:

    标签: angular angular2-template angular2-directives angular-template angular2-ngcontent


    【解决方案1】:

    如果您要向上或向下传递数据超过 1 级,我建议您查看服务并使用主题或行为主题在多个组件之间传递数据。

    【讨论】:

    • 我只是想知道 TemplateRef 没有被孙子识别是什么意思
    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 2019-05-27
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2022-01-12
    相关资源
    最近更新 更多