Resolve Type <> component from string in angular2

Is it possible to get the type of component ( Type<T>) from a value string? Smth like:

let typeStr: string = 'MyComponent';
let type: any = resolveType(typeStr); // actual type
+6
source share
2 answers

You cannot do this without maintaining a “registry” for your classes.

interface Component { }

type ComponentClass = { new (): Component };

const REGISTRY = new Map<string, ComponentClass>();

function getTypeFor(name: string): ComponentClass {
    return REGISTRY.get(name);
}

As for adding entries to this one REGISTRY, you have several options, here are two:

(1) Manually add it after each class definition:

class ComponentA implements Component { ... }
REGISTRY.set("ComponentA", ComponentA);

Or create a function for it:

function register(cls: ComponentClass): void {
    REGISTRY.set(cls.name, cls);
}

class ComponentA implements Component { ... }
register(ComponentA);

(2) Use a decorator:
Just use the above function registeras a decorator:

@register
class ComponentA implements Component { ... }
+7
source

- , . .

.

:

import { Type } from '@angular/core';

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

Source: https://habr.com/ru/post/1672909/


All Articles