Ansuman
Ansuman

Reputation: 1494

Dynamically loading child components in Angular 5

I want to dynamically load the child components in angular. Parent component will load the child components based on some conditions.

Is it possible that we define the child component names in parent component typescript file and in HTML we use string interpolation to load the component?

For example in parent component typescript:

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

And in HTML

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

I tried this but it's not working. Would appreciate any help on this!

Upvotes: 4

Views: 5691

Answers (1)

Andreq Frenkel
Andreq Frenkel

Reputation: 1208

First approach:

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

Second approach 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();
    }
}

Children components should be declared as Entry components

Upvotes: 5

Related Questions