Javascript ng中的ng模板只创建一次
我正在使用动态表单加载器angular 6 我怎样才能做得正确?第一项第一部分,第二项第二部分等? 现在,在第一项中有两个组件。其他项目是空的 编辑:答案 通过使用@ViewChildren解决了这个问题Javascript ng中的ng模板只创建一次,javascript,angular,typescript,Javascript,Angular,Typescript,我正在使用动态表单加载器angular 6 我怎样才能做得正确?第一项第一部分,第二项第二部分等? 现在,在第一项中有两个组件。其他项目是空的 编辑:答案 通过使用@ViewChildren解决了这个问题 @ViewChildren(ProductFormDirective) pfHost: QueryList<ProductFormDirective>; 然后在loadComponents中按索引进行迭代 for (let i = 0; i < this.i
@ViewChildren(ProductFormDirective) pfHost: QueryList<ProductFormDirective>;
然后在loadComponents中按索引进行迭代
for (let i = 0; i < this.item.fields.length; i++) {
const item = this.item.fields[i];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
const pfHostToArray = this.pfHost.toArray();
const viewContainerRef = pfHostToArray[i].viewContainerRef;
const componentRef = viewContainerRef.createComponent(componentFactory);
console.log('component created');
const inst = <ProductFormInnerComponent>componentRef.instance;
(<ProductFormInnerComponent>componentRef.instance).metadata = item;
item.componentRef = componentRef;
}
我有一种烦人的感觉,您在这里并没有为您的用例使用正确的方法。。。你想要实现什么,为什么?从功能上来说,我是说
无论如何,组件中的for循环将只找到与pf主机选择器匹配的第一个视图子级,因此它将仅在第一个视图子级中创建组件 请使用注释进行建议我要创建一个表。此带有ngFor的div创建此表的行。LoadComponent根据其类型创建输入组件。它调用了4次,例如在div中调用ngFor。我希望loadComponent中的第一个组件将位于第一个div中,第二个位于第二个div中,等等。
@ViewChildren(ProductFormDirective) pfHost: QueryList<ProductFormDirective>;
for (let i = 0; i < this.item.fields.length; i++) {
const item = this.item.fields[i];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
const pfHostToArray = this.pfHost.toArray();
const viewContainerRef = pfHostToArray[i].viewContainerRef;
const componentRef = viewContainerRef.createComponent(componentFactory);
console.log('component created');
const inst = <ProductFormInnerComponent>componentRef.instance;
(<ProductFormInnerComponent>componentRef.instance).metadata = item;
item.componentRef = componentRef;
}