假设发出了一个Web请求,它返回了一种类型的项目列表。我有一个Angular组件,用于呈现指定类型的数据。现在,如何将组件实例初始化为从Web请求获取的每个项目并以表格格式呈现它?
我没有自己做,也没有在网上获得任何有用的信息。能否请你帮忙? 提前谢谢!
@ViewChild('container', {read: ViewContainerRef}) container;
constructor(public resolver: ComponentFactoryResolver) {
}
clicked(event) {
const addressFactory = this.resolver.resolveComponentFactory(AddressComponent);
const addressRef = this.container.createComponent(addressFactory);
addressRef.instance.title = 'Home';
}
我能做到这一点。但'容器'参考将变为硬编码。我想为返回的每个项动态创建一个add,并在其中插入填充的AddressComponent。我不能硬编码参考,因为我的动态。
答案 0 :(得分:0)
import {
Injectable,
Injector,
ComponentFactoryResolver,
EmbeddedViewRef,
ApplicationRef
} from '@angular/core';
@Injectable()
export class DomService {
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector
) { }
appendComponentToBody(component: any) {
// 1. Create a component reference from the component
const componentRef = this.componentFactoryResolver
.resolveComponentFactory(component)
.create(this.injector);
// 2. Attach component to the appRef so that it's inside the ng component tree
this.appRef.attachView(componentRef.hostView);
// 3. Get DOM element from component
const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
// 4. Append DOM element to the body
document.body.appendChild(domElem);
// 5. Wait some time and remove it from the component tree and from the DOM
setTimeout(() => {
this.appRef.detachView(componentRef.hostView);
componentRef.destroy();
}, 3000);
}
}