【问题标题】:Dynamically loading child components in Angular 5在 Angular 5 中动态加载子组件
【发布时间】:2019-02-06 15:40:21
【问题描述】:

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

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

例如在父组件打字稿中:

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

在 HTML 中

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

我试过了,但它不起作用。非常感谢您对此的任何帮助!

【问题讨论】:

标签: angular angular5


【解决方案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 components

【讨论】:

猜你喜欢
  • 2018-08-12
  • 2019-10-19
  • 2018-09-15
  • 2020-04-17
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 2018-07-02
  • 2018-11-16
相关资源
最近更新 更多