angular - 组件不会动态创建到使用 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 标签上方创建组件。我做错了什么?
解决方案
你可以做
createSideBarComp() {
this.dynamicSidebar.createComponent(this.factoryResolver.resolveComponentFactory(KSideBarComponent));
}
问题是您没有附加到您采用的侧边栏参考(dynamicSideBar)。但是您正试图通过构造函数附加到为组件注入的 viewContainerRef。这不是您要创建组件的地方。
推荐阅读
- java - Spring Boot REST Api - 响应数据未显示使用实体类之间的 1:M 关系的预期结果
- python - 如何从 2 个列表创建一个 numpy 数组
- node.js - Node.js 应用程序 nodemailer/mailgun 传输在托管时不起作用
- algorithm - 哈希字符串到一个数字 % 16
- python - 从数据框名称列表中连接多个数据框
- angular - 不会破坏应用程序的 Angular 处理 Http 请求错误
- oauth - 有没有一种简单的方法可以授予自己 oauth 访问权限?
- apache-kafka - kafkacat 使用指定范围记录的语法
- javascript - 尝试使用 Javascript 获取 CheckBox 的文本
- linux - 尝试全局安装 expo ubuntu 时出现“找不到命令”