让我说我有一个API给了我这个:
{
title: 'title1',
type: 'FullComponent'
},
{
title: 'title2',
type: 'HalfComponent'
},
{
title: 'title3',
type: 'HalfComponent'
},
{
title: 'title4',
type: 'ThirdComponent'
},
{
title: 'title5',
type: 'ThirdComponent'
},
{
title: 'title6',
type: 'ThirdComponent'
},
我想根据type
值动态生成组件。
// app.component.ts
ngOnInit() {
this.getWidget()
.subscribe(
data => {
},
error => {
???
}
);
}
getWidget() {
return this.http.get('www.api.com');
}
data
返回上面的json。
我应该怎么做才能生成这些组件(这些组件已经使用Angular CLI创建,因此它们已经存在)?
谢谢:))
答案 0 :(得分:0)
我创建了一个组件管理器,它可以根据输入呈现FullComponent,HalfComponent或ThirdComponent:
manager.component.html
<ng-container *ngIf="component === 'FullComponent'">
<app-full-component></app-full-component>
</ng-container>
<ng-container *ngIf="component === 'HalfComponent'">
<app-half-component></app-half-component>
</ng-container>
<ng-container *ngIf="component === 'ThirdComponent'">
<app-third-component></app-third-component>
</ng-container>
manager.component.ts
应该有一个输入:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-manager',
templateUrl: './manager.component.html',
styleUrls: ['./manager.component.css']
})
export class ManagerComponent implements OnInit {
@Input() component: string;
constructor() { }
ngOnInit() {
}
}
在app.component.ts
中将数据传递给数组:
// app.component.ts
data: Any[] = [];
ngOnInit() {
this.getWidget()
.subscribe(
data => {
this.data = data;
},
error => {
???
}
);
}
getWidget() {
return this.http.get('www.api.com');
}
最后,在app.component.html
中,您调用*ngFor
来迭代数据并将type
传递给经理组件:
<ng-container *ngFor='let d of data'>
<app-manager [component]="d.type"></app-manager>
</ng-container>