angular - 动态组件在 ViewInit 后加载时不起作用
问题描述
为什么下面的代码不起作用?为什么@ViewChildren
无法检测到ng-container
s?
HTML
<div [innerHtml]="html"></div>
控制器:
import { Component, ViewChildren, AfterViewInit, QueryList,ViewContainerRef, ComponentFactoryResolver, Injector } from '@angular/core';
import { HelloComponent } from './hello.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChildren('helloComponent',{read: ViewContainerRef}) components: QueryList<ViewContainerRef>
html = "<ng-container #helloComponent></ng-container><ng-container #helloComponent></ng-container>";
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector
){
}
ngAfterViewInit() {
var i = 0;
this.components.forEach(hello => {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent);
var componentRef = hello.createComponent(componentFactory);
componentRef.instance.name = i.toString();
i++;
});
}
}
这是演示:https ://stackblitz.com/edit/angular-8-dynamic-components-not-working
解决方案
@ViewChildren 应该指的是其中有孩子的父母:
<ng-container #helloComponents>
<ng-container>
</ng-container>
<ng-container>
</ng-container>
<ng-container>
</ng-container>
</ng-container>
推荐阅读
- port - 打开防火墙端口到火鸟服务
- java - 在 SAP PI 中进行 base64 解码时,打开/关闭标签被替换为 > <
- django - Django - 上一个请求的访问参数
- javascript - Javascript:通过获取本机函数来防止函数覆盖
- mysql - 如何使用like在sql上选择限制性数据
- php - 如何使用 PHP 在下拉菜单中仅显示具有相同 page_id 的元素?如何在 foreach 循环中编写“if”语句?
- cmake - CMake 命令行参数持久化
- php - UUID Spatie/Laravel-Permission SyncPermission 不工作
- ios - 从字符串解析日期在 IOS 12.4 上不起作用
- arrays - 跳过字节数组