Reputation: 1494
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
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