在Angular 14中,当使用innerHtml动态添加NgbAccordion时,可能无法渲染。这是因为Angular的内容投影机制需要在组件的模板中定义投影位置。为了解决这个问题,可以使用Angular的ComponentFactoryResolver动态创建NgbAccordion组件,然后将其添加到模板中。
示例代码:
import { Component, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
constructor(private componentFactoryResolver: ComponentFactoryResolver, private viewContainerRef: ViewContainerRef) {}
const accordionFactory = this.componentFactoryResolver.resolveComponentFactory(NgbAccordion); const accordionComponentRef = this.viewContainerRef.createComponent(accordionFactory); const accordion = accordionComponentRef.instance; // 设置accordion的属性 accordion.someProperty = someValue; // 添加accordion到模板中 this.viewContainerRef.insert(accordionComponentRef.hostView);
这样,可以在动态添加ngb-accordion到innerHtml时进行渲染,同时可以通过设置属性对accordion进行进一步的配置。
上一篇:Angular14ngb-accordionnotrenderingthroughinnerHtml
下一篇:Angular14nglintisgivingyoungobjectpromotionfailedAllocationfailed,如何解决?