比如说,我有一个 <hook>
以编程方式创建子组件的组件,我如何将内容(Angular 将渲染到钩子(Hook)模板中的 <ng-content></ng-content>
中)作为 ng-content 传递给该子组件(可能会或可能不会决定显示它)? p>
<hook ...>
Dynamic content should be passed to hook's programmatically created child
</hook>
我找到了very helpful explanation关于内容投影,它展示了如何将投影内容传递到以编程方式创建的组件,这是我的问题的一半。对我来说缺少的链接仍然是:如何访问传递给 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();
}
}
hook-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>;
}
如您所见,我可以通过将 hook
的 ng-content
包装到 ng-template
中来获取它。然后,我可以简单地查询该模板并将其传递给以编程方式创建的子模板。
关于angular - 以编程方式将投影内容传递给 child ? (否则将被渲染成 <ng-content> ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748799/