Angular CDK:如何在ComponentPortal中设置输入 [英] Angular CDK: How to set Inputs in a ComponentPortal
问题描述
我想使用CDK中的新 Portal 在其中注入动态内容表单的多个部分.
I would like to use the new Portal from material CDK to inject dynamic content in multiple part of a form.
我有一个复杂的表单结构,目标是要有一个表单,该表单指定子组件可以(或不能)注入模板的多个位置.
I have a complex form structure and the goal is to have a form that specify multiple place where sub components could (or not) inject templates.
也许CDK门户网站不是最佳解决方案?
Maybe the CDK Portal is not the best solution for this?
我尝试了一些方法,但是我确定这不是这样做的方法: https://stackblitz.com/edit/angular-yuz1kg
I tried something but I am sure it is not the way of doing: https://stackblitz.com/edit/angular-yuz1kg
我也尝试过使用new ComponentPortal(MyPortalComponent)
,但是如何设置输入呢?通常是componentRef.component.instance.myInput
I tried also with new ComponentPortal(MyPortalComponent)
but how can we set Inputs on it ? Usually is something like componentRef.component.instance.myInput
推荐答案
您可以创建自定义注入器并将其注入到您创建的组件门户中.
You can create a custom injector and inject it to the component portal you create.
createInjector(dataToPass): PortalInjector {
const injectorTokens = new WeakMap();
injectorTokens.set(CONTAINER_DATA, dataToPass);
return new PortalInjector(this._injector, injectorTokens);
}
CONTAINER_DATA
是由-
export const CONTAINER_DATA = new InjectionToken<{}>('CONTAINER_DATA');
要消耗创建的注射器,请使用-
To consume created injector, use -
let containerPortal = new ComponentPortal(ComponentToPort, null, this.createInjector({
data1,
data2
}));
overlay.attach(containerPortal);
overlay
是OverlayRef
的实例(这是门户出口)
overlay
is an instance of OverlayRef
(Which is Portal Outlet)
在ComponentToPort
内部,您需要注入创建的注入器-
Inside ComponentToPort
, you will need to inject the created injector -
@Inject(CONTAINER_DATA) public componentData: any
有关此此处的更多信息.
这篇关于Angular CDK:如何在ComponentPortal中设置输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!