我有这个数组:
this.dashboard = [
{name: '<app-incassi-provvigioni></app-incassi-provvigioni>'},
{name: '<app-scheda-punti-vendita></app-scheda-punti-vendita>'}
]
我在ngOnInit循环中填充此数组。我想知道当我在html中读取我的数组时如何渲染组件:
<gridster [options]="gridsterOptions">
<gridster-item [item]="item" *ngFor="let item of dashboard">
<!-- your content here -->
{{item.name}}
</gridster-item>
</gridster>
当然现在它返回对象中包含的字符串,但我正在尝试找到一个呈现组件的解决方案。有可能这样做吗?
更多细节:我正在开发一个仪表板类型的应用程序,我从数据库中检索用户dashlet的列表,并且我试图在主应用程序组件准备好后动态呈现这些组件。使用Angular 7和Gridster2。
也许你可以使用角度开关:
<div [ngSwitch]="item.name">
<app-incassi-provvigioni *ngSwitchCase="incassi"></app-incassi-provvigioni>
<app-scheda-punti-vendita *ngSwitchCase="scheda"></app-scheda-punti-vendita>
</div>
而是传递组件标记名称(在您的情况下为“app-incassi-provvigioni”),传递组件名称(TestComponenet),然后从视图中调用该函数并使用Directive动态呈现它。
例如:
<gridster [options]="gridsterOptions">
<gridster-item [item]="item" *ngFor="let item of dashboard">
<div class="inner">
<ng-template dynamic-template> </ng-template>
</div>
</gridster-item>
</gridster>
dynamic-template是一个指令,可以帮助我们加载组件。
this.dashboard = [
{name: 'dashboard1'},
{name: 'dashboard2'}
]
<gridster [options]="gridsterOptions">
<gridster-item [item]="item" *ngFor="let item of dashboard">
<ng-container *ngIf="item.name === 'dashboard1'" *ngTemplateOutlet="dashboard1">
</ng-container>
<ng-container *ngIf="item.name === 'dashboard1'" *ngTemplateOutlet="dashboard2">
</ng-container>
</gridster-item>
</gridster>
<ng-template #dashboard1>
<app-incassi-provvigioni></app-incassi-provvigioni>
</ng-template>
<ng-template #dashboard2>
<app-scheda-punti-vendita></app-scheda-punti-vendita>
</ng-template>
你可以注入组件dynamically
只需使用@Input()组件创建组件;
export class DynamicContentComponent implements OnInit {
@Input() component: any;
@Input() data: any;
constructor(public viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.component);
this.viewContainerRef.clear();
const componentRef = this.viewContainerRef.createComponent(componentFactory);
(<DynamicComponentRef>componentRef.instance).data = this.data;
}
}
并在HTML中使用它
<app-dynamic-content [component]="someComponent" [data]="data"></app-dynamic-content>
数据示例
someComponent = SchedaPuntiVendita;
动态组件应添加到entryComponents
中的module
你也可以创建一些factory
,它将接收一些字符串,并依赖它返回组件类
工厂的例子
@Injectable()
export class DynamicContentComponentFactory {
constructor() { }
get(type: ContentType): any {
switch (type) {
case 'scheda':
return SchedaPuntiVendita;
}
}
并稍微修改DynamicContentComponent
@Input() contentType: string;
constructor(..., private factory: DynamicContentComponentFactory) { }
...
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.factory.get(this.contentType));
...