首页 文章

角2 |打字稿|将字符串映射到组件名称并返回组件

提问于
浏览
1

我得到了在某些条件下我想要替换的组件列表:

导航组件列表:

import {navigationDefaultComponent} from '';
import {navigationSmoothComponent} from '';
import {navigationMobileComponent} from '';

navigations: [
{component: navigationDefaultComponent},
{component: navigationSmoothComponent},
{component: navigationMobileComponent},
]

我有一个来自API和tel的对象,我应该展示什么组件

const X = {
name: 'John Smith',
navigation: 'navigationDefaultComponent'
}

我这样做了,因为我无法将组件存储在api中 . API无法返回给我一个组件 . 如果有办法请告诉我 . 所以我的目标是有一个const将通过导航对象并基于x.navigation字符串将映射并返回我的组件 .

const nav = ????

1 回答

  • 0

    嗯,这是一个典型的情况 . 您需要使一个组件听取**路由然后使用动态组件加载 . https://angular.io/guide/dynamic-component-loader

    您可以创建一个包含字符串和Component的数组

    let mapping = [
        {'name':'name1', 'component':Component1},
        {'name':'name2', 'component':Component2},
        {'name':'name3', 'component':Component3},
        {'name':'name4', 'component':Component4},
        {'name':'name5', 'component':Component5},
    ];
    

    请注意,Component1,Component2是对Component的直接引用,而不是它们的字符串表示 .

    创建一个指令,包含在AppComponent中

    import { Directive, ViewContainerRef } from '@angular/core';
    @Directive({
        selector: '[app-directive]',
    })
    export class AppDirective {
        constructor(public viewContainerRef: ViewContainerRef) { }
    }
    

    在模板中包含该指令

    <ng-template app-directive></ng-template>
    

    在ts文件中获取对指令的引用

    @ViewChild(AppDirective) appDirective: AppDirective;
    

    现在,在从API获得响应后加载所需的组件

    // let's assume name1 is what API returned
    let component = this.mapping['name1'];
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(mapping[component);
    let viewContainerRef = this.appDirective.viewContainerRef;
    viewContainerRef.clear();
    
    let componentRef = viewContainerRef.createComponent(componentFactory);
    

    我希望这能解决你的问题......

相关问题