gpt4 book ai didi

javascript - Typescript 和 Angular : Type a string to a component class

转载 作者:行者123 更新时间:2023-12-03 01:49:08 25 4
gpt4 key购买 nike

一个函数通过字符串传递我的组件的名称,但我需要它作为实际的组件类:

当前:“我的组件”需要:我的组件

我需要“转换”它,以便它正确通过。我有一个 ngFor 可以输出值,我正在尝试使用管道来转换它:

<div id="grid">
<gridster [options]="options">
<gridster-item [item]="item" *ngFor="let item of dashboard;let i = index;">
<div class="grid-header drag-handle">
<span class="handle-icon"><i class="material-icons">open_with</i></span>
<span class="close-icon" (click)="removePanel(item)"><i class="material-icons">close</i></span>
</div>
<div class="grid-content">
<ndc-dynamic [ndcDynamicComponent]="item.viewType | dynamicComponent"></ndc-dynamic>
</div>
</gridster-item>
</gridster>
</div>

上面是 item.viewType,它来 self 的项目数组。我将值传递给 dynamicComponent 自定义管道。我已将组件导入到我的 dynamic-component.pipe.ts 中。我只需要将字符串更改为指定的 viewType 并返回 typed 值:

import { Pipe, PipeTransform } from '@angular/core';
//pulling in all the possible components
import * from '../../views';

@Pipe({
name: 'dynamicComponent'
})
export class DynamicComponentPipe implements PipeTransform {

transform(value: string): any {


}

}

最佳答案

您需要手动创建字符串值和组件之间的映射。组件实际上是命名函数,在编译生产时可以将其最小化为较短的变量名称。

import ComponentA from '../views/ComponentA'; 
import ComponentB from '../views/ComponentA';

const componentMap = {
'ComponentA': ComponentA,
'ComponentB': ComponentB
};

@Pipe({name: 'dynamicComponent'})
export class DynamicComponentPipe implements PipeTransform {
transform(value: string): any {
if(componentMap[value]) {
return componentMap[value];
}
throw new Error(`${componentMap} component was not found`);
}
}

更新:

在运行时使用组件名称的问题是它可以最小化为更小的变量名称以用于生产。因此,当 MyComponent 重命名为 a12 之类的内容时,执行诸如 views['MyComponent'] 之类的操作将不起作用。

另一种方法是使用组件的选择器字符串值来选择组件。 Angular 中的每个组件都必须是唯一的选择器字符串。因此,这是一个可以用作 key 的安全值。

您可以通过 __annotations__ 属性访问(至少在 Angular 5 中)组件的元数据。该属性是一个包含元数据的数组。

所以你可以尝试这样的事情:

import * as views from '../views';

@Pipe({name: 'dynamicComponent'})
export class DynamicComponentPipe implements PipeTransform {
transform(value: string): any {
const view = views.filter((component)=>component['__annotations__'][0]['selector'] === value));
if(view) {
return view;
}
throw new Error(`A component with selector "${value}" was not found`);
}
}

此外,您可以通过直接访问 ngModule 并迭代所有组件来查找匹配的选择器,从而不再需要 views 文件。模块将具有相同的 __annotations__ 属性。

关于javascript - Typescript 和 Angular : Type a string to a component class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50494731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com