Angular 使用viewContainerRef加载动态组件会得到未定义的结果
我已经创建了一个在视图中使用视图的应用程序,我很难将代码移动到库中,然后共享代码 我的主页使用loadChildren路由,然后实际加载要查看的组件。我的页面都共享一个公共导航组件,该组件通过监视可观察对象提供标题栏、侧菜单、自动隐藏、调整大小等功能 因此,我的布线的主要路径是NavigationComponent,这是简单的角度材质导航示意图。然后它有一个路由器出口,它将显示我的目标组件 我的主页是材料仪表板示意图。这些显示卡中包含信息,并路由到标准URL以加载实际组件 例如,我的主页有导航,然后是一系列卡片,显示关于站点、事件、新闻等的不同数据Angular 使用viewContainerRef加载动态组件会得到未定义的结果,angular,angular-material,angular-directive,Angular,Angular Material,Angular Directive,我已经创建了一个在视图中使用视图的应用程序,我很难将代码移动到库中,然后共享代码 我的主页使用loadChildren路由,然后实际加载要查看的组件。我的页面都共享一个公共导航组件,该组件通过监视可观察对象提供标题栏、侧菜单、自动隐藏、调整大小等功能 因此,我的布线的主要路径是NavigationComponent,这是简单的角度材质导航示意图。然后它有一个路由器出口,它将显示我的目标组件 我的主页是材料仪表板示意图。这些显示卡中包含信息,并路由到标准URL以加载实际组件 例如,我的主页有导航,
const routes:Routes = [
{ path: '', component: NavigationCommonComponent,
children: [
{ path: '', component: HomeComponent },
{ path: 'aboutus', component: AboutComponent },
{ path: 'events', component: EventsComponent },
{ path: 'news', component: NewsComponent },
]
}
];
上面的基本路由将提供一些信息。当这些只是卡片时,一切都很好。我已经将卡片移动到库中,数据可以显示在卡片上。我现在要做的,实际上是显示卡数据中组件的内容
例如,如果卡是硬编码的,您将使用
<mat-card>
<appEvents></AppEvents>
</mat-card>
HeroJobad组件
@Component({
template: `
<div class="job-ad">
<h4>{{data.headline}}</h4>
{{data.body}}
</div>
`
})
export class HeroJobAdComponent implements AdComponent {
@Input() public data:any;
}
除了代码运行时,ViewChild中的viewContainerRef显示为:
@ViewChild(AdDirective, {static: true, read: ViewContainerRef}) public adHost:AdDirective;
在常量viewContainerRef=this.adHost.viewContainerRef中显示为null;线附加项未定义
public loadComponent() {
this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
const adItem = this.ads[this.currentAdIndex];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
const viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
(componentRef.instance as AdComponent).data = adItem.data;
}
我相信这与组件的级别有关,我将网格/卡片列表材质仪表板示意图作为导航组件的子级。我不知道如何使此元素不被未定义。删除read:ViewContainerRef属性
public loadComponent() {
this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
const adItem = this.ads[this.currentAdIndex];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
const viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
(componentRef.instance as AdComponent).data = adItem.data;
}
public loadComponent() {
this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
const adItem = this.ads[this.currentAdIndex];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
const viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
(componentRef.instance as AdComponent).data = adItem.data;
}