angular - 如何动态渲染表格布局中的角度组件?
问题描述
假设发出了一个 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 a 并将填充的 AddressComponent 插入其中。我不能对引用进行硬编码,因为我的 ' 是动态的。
解决方案
没关系!我在深度谷歌搜索后找到了答案!
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);
}
}
推荐阅读
- xml - XSLT:如何检查 URL 中存在的特定协议或字符串
- c++ - 如何将着色器嵌入到 UWP-DLL 库中?
- sql - 需要编写一个查询来显示员工全名专业数量并将新列命名为专业
- python - Python:从文档中找出 + 和扩展之间的区别
- macos - 我真的需要实现outlineView(_:objectForValue:byItem:)吗?如何?
- swift - 此 libswiftCore.dylib 副本需要 12.2.0 之前的操作系统版本 - react-native-whatsapp-stickers
- jquery - 如何在单击时将两个不同的活动类添加到两个不同的选项卡(它在图像上的外观)
- laravel - 如何使用 laravel Eloquent 关系获得社区关注者
- elasticsearch - ElasticSearch:按术语查找项目,如果不存在则忽略它
- java - 添加谷歌登录firebaseui时应用程序崩溃