以编程方式将投影内容传递给 children? (否则将呈现为 <ng-content>)

Programmatically pass on projected content to children? (that would be rendered into a <ng-content> otherwise)

说,我有一个 <hook> 组件,它以编程方式创建 child,我如何传递内容(Angular 会呈现为 <ng-content></ng-content>模板)作为 ng-content 改为 child 组件(可能决定显示也可能不显示)?

<hook ...>
   Dynamic content should be passed to hook's programmatically created child
</hook>

我发现了一个关于内容投影的 very helpful explanation,它展示了如何将投影内容传递给以编程方式创建的组件,这是我的问题的一半。对我来说缺少的 link 仍然是:如何访问传递给 hook 的内容以传递它。

如果我完全理解这个问题,这里可能是一个解决方案:

app.component.ts

@Component({
  selector: 'my-app',
  template: `
    <h1>App comp</h1>

    <hook>
      awesome content here
    </hook>
  `
})
export class AppComponent  { }

hook.component.ts

@Component({
  selector: 'hook',
  template: `
    <h2>Hook comp</h2>

  <ng-template #content>
    <ng-content></ng-content>
  </ng-template>

  <ng-container #vc></ng-container>
  `
})
export class HookComp {
  @ViewChild('content', { static: true, read: TemplateRef })
  contentTpl: TemplateRef<any>;
  @ViewChild('vc', { static: true, read: ViewContainerRef })
  vc: ViewContainerRef;

  constructor (
    private cfr: ComponentFactoryResolver,
    private injector: Injector,
  ) { }

  ngAfterViewInit () {
    this.createChildComp();
  }

  private createChildComp () {
    const compFactory = this.cfr.resolveComponentFactory(HookChildComp);
    const componentRef = this.vc.createComponent(compFactory);

    componentRef.instance.contentTpl = this.contentTpl;

    componentRef.changeDetectorRef.detectChanges();
  }
}

勾-child.component.ts

@Component({
  selector: 'hook-child',
  template: `
    <h3>Hook child comp</h3>

    <ng-container *ngTemplateOutlet="contentTpl"></ng-container>
  `
})
export class HookChildComp {
  contentTpl: TemplateRef<any>;
}

如您所见,我可以通过将 hookng-content 包装成 ng-template 来获取它。然后,我可以简单地查询该模板并将其传递给以编程方式创建的子项。