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

时间:2017-10-02 10:39:38

标签: json angular typescript object

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

导航组件列表:

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 :(得分: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);

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