首页 > 解决方案 > 有没有办法从不同的目录获取组件?

问题描述

我正在尝试在与我的主项目不同的项目中创建动态组件,并在运行时加载它。问题是如果它位于不同的目录中,我不知道如何获取该组件。

这是来自https://denys.dev/2016-11-27/dynamic-content-in-angular/的想法

@Component({
    selector: 'runtime-content',
    template: `
        <div>
            <h3>Template</h3>
            <div>
                <textarea rows="5" [(ngModel)]="template"></textarea>
            </div>
            <button (click)="compileTemplate()">Compile</button>
            <h3>Output</h3>
            <div #container></div>
        </div>
    `
})
let metadata = {
            selector: `runtime-component-sample`,
            template: this.template
        };

        let factory = this.createComponentFactorySync(this.compiler, metadata, null);

到目前为止,我所拥有的是基于运行时内容组件中显示的 textarea 内写入的任何内容创建组件,并将其放入元数据中。

private createComponentFactorySync(compiler: Compiler, metadata: Component, componentClass: any): ComponentFactory<any> {
        const cmpClass = componentClass || class RuntimeComponent { name: string = 'Denys' };
        const decoratedCmp = Component(metadata)(cmpClass);

        @NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
        class RuntimeComponentModule { }

        let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
        return module.componentFactories.find(f => f.componentType === decoratedCmp);
    }

但我需要的是如何基于项目之外的其他一些 ts 文件创建元数据?

标签: angular

解决方案


推荐阅读