我有一个组件,我想在子组件中显示可配置的html.客户端无法访问子组件.所以我想我要找的是content projection

<Parent>
 <ng-template #editTemplate> //custom 
   <button>Edit Me </button>
 </ng-template>    
 <child1>
     ...
     <child4>
       I would like to show the #editTemplate here
     </child4>
 </child1>
</Parent>

所以在child4以内

我有这个HTML

<div>
  <ng-content #editTemplate></ng-content>
</div>

但是,我无法显示按钮.我做错了什么?

推荐答案

这里有一个有趣的内容投影和依赖注入的组合.

<ng-template #editTemplate>正在将内容投影到Parent组件中

<Parent>
 <ng-template #editTemplate> <--- projected into <Parent>
   <button>Edit Me </button>
 </ng-template>
</Parent>

所以Parent通过Content Child直接引用它,如果Parent组件看起来像这样:

@Component({
  selector: 'parent',
  template: `
  <h2>Parent here!</h2>

  <ng-content></ng-content> <--- #editTemplate will get projected here

  <child1></child1>
  `,
  styles: [`h1 { font-family: Lato; }`],
})
export class ParentComponent {
  @ContentChild('editTemplate') editTemplate: TemplateRef<any>; // <--- reference to #editTemplate
}

然而,child4嵌套了好几层,因此依赖注入在这里是您的朋友,否则您需要配置一个引用in each layer来完成从Parentchild4的链.

不过,使用DI,您可以将Parent组件直接注入child4,然后child4可以访问Parent组件实例上的editTemplate引用,并使用*ngTemplateOutlet插入TemplateRef中的视图.

所以child4个可能是这样的:

@Component({
  selector: 'child4',
  template: `
  <h3>Child 4 here!</h3>
  <div>And here's the injected template:</div>

  <ng-container *ngTemplateOutlet="projectedTemplate"></ng-container> <--- use *ngTemplateOutlet to render editTemplate
  `,
  styles: [`h1 { font-family: Lato; }`],
})
export class Child4Component {
  projectedTemplate: TemplateRef<any>;

  constructor(private parentComponent: ParentComponent) {} // <-- inject ParentComponent instance

  ngOnInit() {
    this.projectedTemplate = this.parentComponent.editTemplate; // <-- set *ngTemplateOutlet to editTemplate
  }
}

Here's a StackBlitz显示此方法.

Angular相关问答推荐

如何在init为FALSE时以Angular 初始化主拇指擦除器-Swiper 11.0.6Angular 17 SSR

有Angular react 形式的输入用货币管

Angular 17:在MouseOver事件上 Select 子组件的正确ElementRef

无法匹配任何路由.URL段:';英雄';

一次重定向后,所有子路由都处于活动状态

Angular 迁移 14 到 15 / 16:angular universal 是否停止将 <!-- this page was prerendered with angular universal --> 用于预渲染页面?

如何禁用特定数据集图表js的默认标签

模块AppModule导入的意外指令LoginComponent,请添加@NgModule 注释

如何在 Angular 2 应用程序中配置不同的开发环境

Angular url加号转换为空格

等待多个promises完成

如何从组件模板将数组作为 Input() 传递?

Angular 2如何让子组件等待异步数据准备好

Angular2 - 如何开始以及使用哪个 IDE

Angular 2:formGroup 需要一个 FormGroup 实例

如何在 Angular 2 的同一个组件中使用多个 ng-content?

如何在 Angular 4 中翻译 mat-paginator?

Angular 4.3 HttpClient:拦截响应

Angular 9 引入了需要加载的全局$localize()函数

如何使用 Angular CLI 删除包?