Angular2 - 将参数传递给动态生成的组件?

Roy*_*mir 4 javascript angular

我有一个简单的演示应用程序,我正在模拟从DB手动插入/获取数据并注入新组件 - 根据输入的数字.

Plunker

在此输入图像描述

所以如果我点击"手动"按钮两次:

在此输入图像描述

如果我在文本中设置"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);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是Injected组件:

//src/TestPage.ts
@Component({
  selector: 'test-component',
  template: '<b>Content  : Name={{user.Name}} Age={{user.Age}}</b><br/>',
})
export class TestPage {
    @Input
     User:Person;

}
Run Code Online (Sandbox Code Playgroud)

那问题出在哪里?

如您所见,在注入的组件中,我有:

@Input
User:Person;
Run Code Online (Sandbox Code Playgroud)

这意味着我希望parent组件将Person对象传递给每次注入.

换一种说法 :

看看"后db阶段",我怎样才能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` ???

    }
  })

}
Run Code Online (Sandbox Code Playgroud)

预期产量:

在此输入图像描述

NB我不想使用,ngFor因为我不需要在后端持有一个数组.这是一个定期注入新文章的应用程序.我很高兴知道是否有更好的方法.

eko*_*eko 6

您可以使用instance组件引用的属性执行此操作,如下所示:

putInMyHtml(p) {
   // this.target.clear();

    let compFactory = this.cfr.resolveComponentFactory(TestPage);

    let ref = this.target.createComponent(compFactory);
    ref.instance.user = p;
}
Run Code Online (Sandbox Code Playgroud)

- 修复了@Input()绑定,语法错误.

- ?为模板添加了一个安全导航操作符(),以对异步输入进行空检查.

固定的plunker:https://plnkr.co/edit/WgWFZQLxt9RFoZLR46HH p = preview