简体   繁体   English

将字符串转换为类打字稿/角度

[英]Convert string to class typescript/angular

I have a component that is a modal popup.我有一个组件是模态弹出窗口。 It takes a string as an input and then loads other components dynamically.它接受一个字符串作为输入,然后动态加载其他组件。 That way I can have one modal popup component instead of replicating a modal popup code for every modal i need in the app.这样我就可以拥有一个模态弹出组件,而不是为我在应用程序中需要的每个模态复制一个模态弹出代码。 Problem is that this results in a large if/else statement where I load appropriate component based on the string input as such问题是这会导致一个很大的 if/else 语句,在那里我根据字符串输入加载适当的组件

if (this.data.component == "ContactStaffComponent")
  componentFactory = this.componentFactoryResolver.resolveComponentFactory(ContactStaffComponent);
else if (this.data.component == "DocketComponent")
  componentFactory = this.componentFactoryResolver.resolveComponentFactory(DocketComponent);
else if (this.data.component == "FilingComponent")
  componentFactory = this.componentFactoryResolver.resolveComponentFactory(FilingComponent);
else if (this.data.component == "ServiceListRecordComponent")
  componentFactory = this.componentFactoryResolver.resolveComponentFactory(ServiceListRecordComponent);
else { }

Is there a way to convert the string into type?有没有办法将字符串转换为类型? Something along the lines of .net reflection?类似于 .net 反射的东西?

You can create an object with your components你可以用你的组件创建一个对象

private modals = {
    ContactStaffComponent: ContactStaffComponent,
    DocketComponent: DocketComponent
};

Then based on the input string you can get the component and pass it to the component resolver然后根据输入字符串,您可以获取组件并将其传递给组件解析器

let component = this.modals[this.data.component];
componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);

Through this, you can eliminate a large if/else code chunk.通过这个,你可以消除一个大的 if/else 代码块。 Hope this is helpful希望这有帮助

To make the code more succinct, you can declare an Observable of Components in this way:为了使代码更简洁,您可以通过以下方式声明组件的 Observable:

import { of } from 'rxjs';
import { filter } from 'rxjs/operators';

...

export class ... {
  componentList$ = of(
    ContactStaffComponent,
    DocketComponent,
    FilingComponent,
    ServiceListRecordComponent
  );
  ...
}

You can get the name of the component by accessing the .name attribute from componentList$.您可以通过访问 componentList$ 中的 .name 属性来获取组件的名称。 And filter the componentList$ as follows.并按如下方式过滤 componentList$。

this.componentList$.pipe(
  filter(component => this.data.component == component.name.toString()))
  .subscribe((componentName: any) =>{
    componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentName);
  });

Hope this helps.希望这可以帮助。 CYA!青!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM