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! 解决方案 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 这篇关于在Angular 5中动态加载子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-18 09:01