【问题标题】:How to create an Angular compnent dynamically by adding a dynamic name to resolveComponentFactory如何通过向resolveComponentFactory添加动态名称来动态创建Angular组件
【发布时间】:2020-05-11 02:21:16
【问题描述】:

我正在尝试动态调用组件。我有一个将子组件类型作为输入(字符串)的组件。例如 detail.itemType = '手风琴'。我希望这个组件根据类型调用正确的子组件,但不使用 if 语句



import { ContentDetail, ContentFields } from 'app/models/content/content.model';
import { Component, OnInit, Input, ComponentFactoryResolver, ViewChild, ViewContainerRef, ComponentRef } from '@angular/core';
import { AccordionComponent } from './accordion-paragraph/accordion-paragraph.component';

@Component({
  selector: 'app-content-components',
  templateUrl: './content-components.component.html',
  styleUrls: ['./content-components.component.scss']
})
export class ContentComponentsComponent implements OnInit {

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  @ViewChild('createComponent', {static: true, read: ViewContainerRef }) entry: ViewContainerRef;
  @Input() public detail: ContentDetail = new ContentDetail();


  ngOnInit() {
      let component: any = null;
      if(this.detail.itemType === 'Accordion'){
        component = AccordionComponent;
        let factory = this.componentFactoryResolver.resolveComponentFactory(component);
        let componentRef:ComponentRef<any> = this.entry.createComponent(factory);
      }
  }



}

所以我想动态添加 Accordion 而不是使用 if 语句。类似:

   let componentName = Accordion
   component = componentName + Component;
   let factory = this.componentFactoryResolver.resolveComponentFactory(component);
   let componentRef:ComponentRef<any> = this.entry.createComponent(factory);

是否可以添加这样的组件名称?

【问题讨论】:

标签: angular typescript


【解决方案1】:

根据this.detail.itemType创建一个返回组件名的服务,然后使用这个代码:

    let component = this.contentService.getComponentbytype(this.detail.itemType)
    if(component){
      let factory = this.componentFactoryResolver.resolveComponentFactory(component);
      let componentRef:ComponentRef<any> = this.entry.createComponent(factory);
      componentRef.instance.fields = this.fields;
    }

在您的服务文件中:

public getComponentbytype(_itemType: string): any {
let component: any;

if (_itemType) {
    switch (_itemType) {
        case 'specificItemType':{
            component = specificItemTypeComponent;
            break;
        }
        default: {
            component = null;
            break;
        }
    }
}

return component
}

【讨论】:

  • 能否请您在回答中包含该服务
【解决方案2】:

您不能像这样更改组件名称,因为 Component 是对象而不是字符串。您可以创建 ComponentArray 它将旧您的所有组件,并根据 contidion 您可以从数组中传递该组件,像这样

myComponents = [comp1, copm2,...]
if(item==='condition')
   let component =  myComponents[0]

【讨论】:

  • 谢谢 Shilpa,如果我没有阵列上的订单怎么办?我怎么知道要调用哪个组件?
  • 将数组更改为对象数组并将itemType与组件一起存储,当它与选定的itemType匹配时,您可以遍历数组返回该组件。
猜你喜欢
  • 2018-08-28
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 2019-09-30
  • 2018-04-30
  • 1970-01-01
  • 2017-07-17
相关资源
最近更新 更多