Benson
Benson

Reputation: 125

Resolving component from class name in Angular 4

Is it possible to resolve a component from string?

Previously in Angular 2, we are able to do this see here. However, in Angular 4, the same method will throw error.

private resolver: ComponentFactoryResolver

var factories = Array.from(this.resolver['_factories'].keys());
var factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);

Upvotes: 1

Views: 312

Answers (1)

Michael Kang
Michael Kang

Reputation: 52847

It looks like you might be relying on an implementation detail. However, to get around the error, you can explicitly cast the type to any in order to access the indexer. Assuming there is a _factories property, this should work:

var factories = Array.from((<any>this.resolver)['_factories'].keys());

Upvotes: 2

Related Questions