4

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!

1

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like declaring them as entry components is no longer required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.