I am encountering a problem with Angular and the CdkPortal
/CdkPortalHost
from @angular/cdk
.
I developed a service that allows me to associate a CdkPortalHost
with a specified name and set its Component
at any given time.
This is how the service is structured:
private portalHosts : { [location : string] : CdkPortalOutlet } = {};
private portals : { [location : string] : any} = {};
/** Assigns the PortalHost to the designated location. */
public register(location : string, portalHost : CdkPortalOutlet) {
this.portalHosts[location] = portalHost;
}
/** Sets the Component for the specified location. */
public setComponent<T>(location : string, type : ComponentType<T>) : ComponentRef<T> {
let ref : ComponentRef<T> = null;
let portalHost = this.portalHosts[location];
if (portalHost) {
if (portalHost.hasAttached()) {
portalHost.portal.detach();
this.portals[location] = null;
}
ref = portalHost.attachComponentPortal(new ComponentPortal(type));
this.portals[location] = ref.instance;
}
return ref;
}
Next, I registered a PortalHost in this manner:
@ViewChild(PortalHostDirective)
private portalHost : PortalHostDirective;
public ngAfterContentInit() {
this.dynamicComponentService.register("Location", this.portalHost);
}
In another child Component of the one registering the PortalHost, I initialize the dynamic Component using the following code:
public ngAfterContentInit() {
this.dynamicComponentService.setComponent("Location", MyDynamicComponent);
}
For testing purposes, I have a simple template for MyDynamicComponent like so:
<div *ngIf="true">Test</div>
Upon running the application, I encounter the error message below:
Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'undefined'. Current value: 'true'.
It seems like the view has been created after its parent and its children have been dirty checked.
Has it been created in a change detection hook ?
I have looked into similar issues, but the "window.setTimeout" workaround did not resolve the problem for me.
I also attempted different lifecycle hooks for the PortalHost registration and Component creation, but encountered the same issue...
I am currently utilizing Angular 5.0.1 and Material/CDK 5.0.0-rc0.
Am I overlooking something or is this possibly a bug?
Could this be related to Angular/Material#5268