在Angular 5中基于字符串创建动态组件

时间:2017-12-18 12:16:34

标签: angular

让我说我有一个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创建,因此它们已经存在)? 谢谢:))

1 个答案:

答案 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>