在Angular 5中动态加载子组件

时间:2018-08-31 15:06:55

标签: angular angular5

我想按角度动态加载子组件。父组件将根据某些条件加载子组件。

是否有可能在父组件打字稿文件中定义子组件名称,并在HTML中使用字符串插值来加载组件?

例如在父组件打字稿中:

componentName = someCondition ? 'component1' : 'component2';

以HTML

<app-{{componentName}}></app-{{componentName}}

我尝试了这个,但是没有用。希望对此有任何帮助!

1 个答案:

答案 0 :(得分:1)

第一种方法:

<ng-container [ngSwitch]="componentName">
  <component-one *ngSwitchCase="'component1'"></component-one>
  <component-two *ngSwitchCase="'component2'"></component-two>
  ...
</ng-container>

第二种方法componentFactoryResolver

@Component({
    selector: 'parent',
    template: `
        <div #target></div>
    `
})
export class ParentComponent {
    @Input() child: string;
    @Input() value: string;

    //Get tag child component will be placed
    @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
    private componentRef:ComponentRef<any>;

    //Child components
    private children = {
        child1: Child1Component,
        child2: Child2Component
    };

    constructor(private compiler: ComponentFactoryResolver) {}

    //Pass through value to child component
    renderComponent(){
        if (this.componentRef) this.componentRef.instance.value = this.value;
    }

    //Compile child component
    ngAfterContentInit() {
        let childComponent = this.children[this.child || 'child1'];
        //Resolve child component
        let componentFactory = this.compiler.resolveComponentFactory(childComponent);
        this.componentRef = this.target.createComponent(componentFactory);
        this.renderComponent();
    }

    //Pass through value to child component when value changes
    ngOnChanges(changes: Object) {
        this.renderComponent();
    }
}

儿童组件应声明为Entry组件