我有这个数组:
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>
当然,现在它返回对象中包含的字符串,但是我正在尝试找到一种解决方案来呈现组件。 可以做到吗?
更多详细信息: 我正在开发一个仪表板类型的应用程序,从数据库中检索用户仪表板的列表,并尝试在主应用程序组件准备就绪后动态呈现这些组件。 使用Angular 7和Gridster2。
答案 0 :(得分:0)
也许您可以为此使用角度开关:
<div [ngSwitch]="item.name">
<app-incassi-provvigioni *ngSwitchCase="incassi"></app-incassi-provvigioni>
<app-scheda-punti-vendita *ngSwitchCase="scheda"></app-scheda-punti-vendita>
</div>
答案 1 :(得分:0)
而是传递组件标签名称(在您的情况下为“ 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是一个指令,可以帮助我们加载组件。
答案 2 :(得分:0)
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>
答案 3 :(得分:0)
您可以注入组件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));
...