我有一个简单的演示应用程序,我正在模拟手动插入/从数据库获取数据并注入新组件 - 根据输入的数字。
Plunker https://plnkr.co/edit/1YAIa7sEeQCnQW1OmnC7?p=preview
因此,如果我单击“手动”按钮两次:
如果我在文本中设置“3”并单击“从数据库获取”-我会得到预期的延迟(模拟数据库),然后:
这一切都按预期进行。
“父”组件是:
//src/MainPage.ts
@Component({
selector: 'my-app',
template: `
<button (click)="putInMyHtml()">Insert component manually</button>
<p> # Items to fetch : <input type="text" style='width:40px' [(ngModel)]="dbNumItems" name="dbNumItems"/> <input type='button' value='fetch from db' (click)='fetchItems($event)'/></p>
<div #myDiv>
<template #target></template>
</div>
`
})
export class MainPage {
@ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
dbNumItems: string;
constructor(private cfr: ComponentFactoryResolver) {}
fetchItems(){
var p= new Promise((resolve, reject) => { //simulate db
setTimeout(()=>resolve(this.dbNumItems),2000)
});
p.then(v=>{
for (let i =0;i<v;i++)
{
this.putInMyHtml() ;// inject "v" times
}
})
}
putInMyHtml() {
// this.target.clear();
let compFactory = this.cfr.resolveComponentFactory(TestPage);
this.target.createComponent(compFactory);
}
}
这是注入的组件:
//src/TestPage.ts
@Component({
selector: 'test-component',
template: '<b>Content : Name={{user.Name}} Age={{user.Age}}</b><br/>',
})
export class TestPage {
@Input
User:Person;
}
那么问题出在哪里呢?
如您所见,在注入的组件中我有:
@Input
User:Person;
这意味着我想要parent
组件传递一个Person
反对每次注射。
换句话说 :
Question
看看“after db stage”,我怎样才能通过定制的person
每次注射?
p.then(v=>{
for (let i =0;i<v;i++)
{
let p = new Person();
p.Name = "name"+i;
p.Age = i;
this.putInMyHtml() ; //how to I pass `p` ???
}
})
}
预期输出:
注意
我不想用ngFor
因为我不需要在后端保存数组。这是一个定期注入新文章的应用程序。我很高兴知道是否有更好的方法。