首页 > 解决方案 > 动态创建的组件被添加为同级

问题描述

我正在开发一个 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>

在此处输入图像描述

标签: angularionic-framework

解决方案


我通过放置解决了这个问题

<ng-container #instrumentcontainer></ng-container> 

在我所理解的 ion-content 元素内部,在运行时会从 DOM 中删除。


推荐阅读