Angular CDK: How to set Inputs in a ComponentPortal
If you are using Angular 10+ and following Awadhoot's answer, PortalInjector is now deprecated so instead of:
new PortalInjector(this.injector, new WeakMap([[SOME_TOKEN, data]]))
You now have:
Injector.create({
parent: this.injector,
providers: [
{ provide: SOME_TOKEN, useValue: data }
]
})
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
is a custom injector (InjectorToken
) created by -
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
is an instance of OverlayRef
(Which is Portal Outlet)
Inside ComponentToPort
, you will need to inject the created injector -
@Inject(CONTAINER_DATA) public componentData: any