Angular 2/RC5 - Dynamically Loading components

99 views
Skip to first unread message

David Marginian

unread,
Aug 22, 2016, 4:26:31 PM8/22/16
to AngularJS
Now that ComponentResolver is deprecated how can we dynamically load a component and:

1) Insert it based on a dynamic selector string.
2) Pass inputs to the component.

My old code looked like this:

componentPromises.push(this._componentResolver.resolveComponent(WidgetContainerComponent).then((factory: ComponentFactory<any>) => {
let widgetId: string = this._widgetIdPrefix + dashboardItem.widgetConfig.widgetId;
// Dynamically build the selector string.
let selectorString: string = "[id=" + widgetId + "]";
let componentRef = factory.create(this._injector, null, selectorString);
// Manually set the dashboardItem Input so that the WidgetContainer knows how to build itself.
componentRef.instance["dashboardItem"] = dashboardItem;
componentRef.instance["refreshObservable"] = this.refreshObservable;
// Register the component with appRef change detector, this is critical, without it life cycle events, bindings, etc. will not work.
(<any>this._appRef)._loadComponent(componentRef);
}));

The ComponentFactoryResolve doesn't appear to support this and the examples I have seen seem to use a static ViewContainerRef (http://plnkr.co/edit/P0spNzu8JbQad2aKACsX?p=info).

Long Field

unread,
Aug 24, 2016, 2:15:18 AM8/24/16
to AngularJS
Reply all
Reply to author
Forward
0 new messages