angular - 动态创建的组件被添加为同级
问题描述
我正在开发一个 Ionic/Angular 项目,我正在尝试将组件动态添加到页面中。要创建组件,我使用 Angulars ComponentFactoryResolver。将组件添加到视图时,它们被添加为目标容器的同级,而不是子容器。
仪器页面.ts
@Component({
selector: 'app-instruments',
templateUrl: './instruments.page.html',
styleUrls: ['./instruments.page.scss'],
})
export class InstrumentsPage implements AfterViewInit {
instruments: Instrument[];
@ViewChild('instrumentscontainer', { read: ViewContainerRef }) entry: ViewContainerRef;
constructor(
private data: DataService,
private resolver: ComponentFactoryResolver
) {
this.instruments = data.getInstruments();
}
ngAfterViewInit() {
this.createComponents();
}
createComponents() {
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(InstrumentCardComponent);
this.data.getData().forEach((organization: Organization) => {
organization.getGroups().forEach((group: Group) => {
group.getFields().forEach((field: Field) => {
field.getInstruments().forEach((instrument: Instrument) => {
let component = this.entry.createComponent(factory);
component.instance.instrument = instrument;
component.instance.field = field;
console.log(component);
});
});
});
});
}
}
仪器.page.html
<ion-content #instrumentscontainer>
</ion-content>
解决方案
我通过放置解决了这个问题
<ng-container #instrumentcontainer></ng-container>
在我所理解的 ion-content 元素内部,在运行时会从 DOM 中删除。
推荐阅读
- javascript - Javascript 部分初始化
- module - 如何在 rescript 中将类型构造函数设为私有(当前模块除外)?
- pytorch - PyTorch ROCm 已发布 - 如何选择 Radeon GPU 作为设备
- sql - 运算符导致空值问题
- javascript - 如何通过单击删除按钮上的悬停?
- macros - 在卸载模式下使用嵌套在宏中的 StrLoc
- c++ - 如何解释 tensorflow lite c++ 中的输出张量数据打包?
- blazor - 添加记录后EditForm似乎没有更新,为什么
- task - 如何修复任务运行器
- javascript - 如何在 HTML 和 JS 文件中更改 Google Maps Javascript API 的地图 ID?