首页 > 解决方案 > 组件不会动态创建到使用 Angular 中的 ViewChild 指定的 div

问题描述

我正在尝试将组件附加/创建到特定的 div 中。但是,正在创建该组件,但不是我想要的。我做错了什么?

在此处输入图像描述

我希望 k-sidebar 组件位于我在图像中显示的 div 内。

下面是我的代码。

应用程序组件

 import { Component, OnInit, OnDestroy, ViewChild, ElementRef, Renderer2, ViewContainerRef, 
 ComponentFactoryResolver, ComponentRef, ComponentFactory} from '@angular/core';
 @Component({
  selector: 'app-comp',
  templateUrl: './app-comp.component.html',
  encapsulation: ViewEncapsulation.None
 })
 export class AppComponent implements OnInit {
  componentRef: any;
  @ViewChild('dynamicSidebar', {read: ViewContainerRef})
  public dynamicSidebar: ViewContainerRef;

  constructor(private factoryResolver: ComponentFactoryResolver,
   private containerRef: ViewContainerRef) { }

  ngOnInit() {
   this.createSidebarComp();
 }


 createSidebarComp(){
  this.containerRef.clear();
  this.containerRef.createComponent(this.factoryResolver.resolveComponentFactory(KSideBarComponent));
 }
}

HTML

<!-- header test -->
<k-header [navItems]="navItems" [title]="title">
 <ng-template rightSection>
 <k-icon [icon]="testIcon"></k-icon>
</ng-template>
</k-header>
<!-- /header test -->

<div class="container-fluid">
 <div #dynamicSidebar></div>
 <h1>{{title}} app is running!</h1>
 <router-outlet></router-outlet>

</div>

侧边栏位于路由器插座内,我想基于布尔值在 h1 标签上方创建组件。我做错了什么?

标签: angularangular8viewchildangular-dynamic-components

解决方案


你可以做

createSideBarComp() {
     this.dynamicSidebar.createComponent(this.factoryResolver.resolveComponentFactory(KSideBarComponent));
}

问题是您没有附加到您采用的侧边栏参考(dynamicSideBar)。但是您正试图通过构造函数附加到为组件注入的 viewContainerRef。这不是您要创建组件的地方。


推荐阅读