Angular 如何在“角度”选项卡中加载动态组件?
我需要以角度将组件动态加载到选项卡中。我有一个父组件,其中有角度选项卡。在选项卡控件中,我需要动态加载子组件 最初,当加载选项卡时,它应该加载一个组件1,在某些用户交互中,它应该触发事件,该事件将加载其他选项卡和要加载到其中的其他子组件 我的要求是在每个选项卡中动态加载任何子组件 我面临着在选项卡中动态加载子组件的问题,并且不了解如何进一步操作 我已经为中的演示创建了一个POC 我的父组件如下所示:Angular 如何在“角度”选项卡中加载动态组件?,angular,Angular,我需要以角度将组件动态加载到选项卡中。我有一个父组件,其中有角度选项卡。在选项卡控件中,我需要动态加载子组件 最初,当加载选项卡时,它应该加载一个组件1,在某些用户交互中,它应该触发事件,该事件将加载其他选项卡和要加载到其中的其他子组件 我的要求是在每个选项卡中动态加载任何子组件 我面临着在选项卡中动态加载子组件的问题,并且不了解如何进一步操作 我已经为中的演示创建了一个POC 我的父组件如下所示: import {Component, ViewChild, AfterViewInit,
import {Component, ViewChild, AfterViewInit, TemplateRef, ComponentRef, ViewContainerRef} from '@angular/core';
import { ComponentFactoryResolver } from '@angular/core';
import { Component1 } from './Component1';
import { Component2 } from './Component2';
@Component({
selector: 'home',
template: `<mat-tab-group class="demo-tab-group">
<mat-tab *ngFor="let tab of homepageTabs; let i = index" label="{{tab.label}}">
<!--Component1 and Component2 to be loaded here... what is the correct container object which can hold dynamic components ? -->
<ng-template #container>{{tab.templateRef}}</ng-template>
</mat-tab>
</mat-tab-group>`
})
export class HomeComponent {
homepageTabs: any;
@ViewChild('container', { read: ViewContainerRef }) dynamicTabPlaceholder;
constructor(private cfr: ComponentFactoryResolver)
{
//Need to instantiate the components Component1 & Component2 dynamically and load here into the homepageTabs List
const factory = this.cfr.resolveComponentFactory(Component1);
const componentRef = this.dynamicTabPlaceholder.createComponent(factory);
this.homepageTabs = [
{
label: 'HomeLabel',
//templateRef: Component1,//How to assign the component1 instance here?
tabTitle: 'HomeTitle'
},
{
label: 'App Details',
//templateRef: Component2,
tabTitle: 'App Details'
}
];
}
}
我在这里感到震惊,不知道如何加载要加载到选项卡中的子组件:-
{{tab.templateRef}}
对于您动态创建的任何组件,您需要将它们作为entryComponents
添加到您的模块中。这是一个提示,提示编译器在bundle中包含用于创建它们的工厂
@NgModule({
declarations: [
SomeDynamicComponent
],
entryComponents: [
SomeDynamicComponent
]
})
尝试以下方法在另一个组件中加载子组件。我做了如下工作,效果非常好
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(Component1);
const componentRef = this.entry.createComponent(factory);
我认为这里的答案是使用
angular
路由器功能加载您所指的动态内容
关键是我学到了艰难的方法是而不是将应用程序的主要组件设置为路由。因此,不要将路由器插座
放在index.html
文件中,而是作为应用程序组件
的一个元素
通过这种方式,您还可以为应用程序构建一个静态布局,该布局在内部内容更改时保持不变。我的问题与entrycomponents问题无关,而是与可以容纳动态组件的正确容器对象以及如何分配有关。很抱歉造成混淆,我已编辑了我的问题。如果您需要更多信息,请告诉我Hi,是否要动态创建导航选项卡??如果是的,我可以帮你。嗨,克丽珊,你有没有机会看看我的答案?你成功地做到了吗?
@NgModule({
declarations: [
SomeDynamicComponent
],
entryComponents: [
SomeDynamicComponent
]
})
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(Component1);
const componentRef = this.entry.createComponent(factory);