首页 > 解决方案 > 如何动态渲染表格布局中的角度组件?

问题描述

假设发出了一个 Web 请求,它返回了一个类型的项目列表。我有一个 Angular 组件,旨在呈现指定类型的数据。现在,如何将组件实例初始化为从 Web 请求中获取的每个项目,并将其呈现为表格格式?

我自己没有做到这一点,也没有在网络上获得任何有用的信息。能否请你帮忙?提前致谢!

  @ViewChild('container', {read: ViewContainerRef}) container;

  constructor(public resolver: ComponentFactoryResolver) {
  }

  clicked(event) {
    const addressFactory = this.resolver.resolveComponentFactory(AddressComponent);
    const addressRef = this.container.createComponent(addressFactory);
    addressRef.instance.title = 'Home';
   }

我可以做到这一点。但是“容器”引用将变成硬编码。我想为返回的每个项目动态创建一个 add a 并将填充的 AddressComponent 插入其中。我不能对引用进行硬编码,因为我的 ' 是动态的。

标签: angularangular-components

解决方案


没关系!我在深度谷歌搜索后找到了答案!

https://medium.com/@caroso1222/angular-pro-tip-how-to-dynamically-create-components-in-body-ba200cc289e6

import {
    Injectable,
    Injector,
    ComponentFactoryResolver,
    EmbeddedViewRef,
    ApplicationRef
} from '@angular/core';

@Injectable()
export class DomService {

  constructor(
      private componentFactoryResolver: ComponentFactoryResolver,
      private appRef: ApplicationRef,
      private injector: Injector
  ) { }

  appendComponentToBody(component: any) {
    // 1. Create a component reference from the component 
    const componentRef = this.componentFactoryResolver
      .resolveComponentFactory(component)
      .create(this.injector);

    // 2. Attach component to the appRef so that it's inside the ng component tree
    this.appRef.attachView(componentRef.hostView);

    // 3. Get DOM element from component
    const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
      .rootNodes[0] as HTMLElement;

    // 4. Append DOM element to the body
    document.body.appendChild(domElem);

    // 5. Wait some time and remove it from the component tree and from the DOM
    setTimeout(() => {
        this.appRef.detachView(componentRef.hostView);
        componentRef.destroy();
    }, 3000);
  }
}

推荐阅读