如果我完全理解这个问题,这可能是一个解决方案:
app.component.ts
@Component({
selector: 'my-app',
template: `
<h1>App comp</h1>
<hook>
awesome content here
</hook>
`
})
export class AppComponent { }
钩子组件.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();
}
}
钩子.component.ts
@Component({
selector: 'hook-child',
template: `
<h3>Hook child comp</h3>
<ng-container *ngTemplateOutlet="contentTpl"></ng-container>
`
})
export class HookChildComp {
contentTpl: TemplateRef<any>;
}
如您所见,我可以通过将hook
'ng-content
包装成ng-template
. 然后,我可以简单地查询该模板并将其传递给以编程方式创建的孩子。