简体   繁体   English

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

[英]Angular2 - Pass parameters to a dynamically generated component?

I have a simple demo app which I'm simulating manually insert / fetch data from DB and injecting new components - according to the num entered. 我有一个简单的演示应用程序,我正在模拟从DB手动插入/获取数据并注入新组件 - 根据输入的数字。

Plunker Plunker

在此输入图像描述

So if I click the "manual " button twice : 所以如果我点击“手动”按钮两次:

在此输入图像描述

And if I set "3" in the text and click "fetch from db" - I get the expected delay(simulate db) and then : 如果我在文本中设置“3”并单击“从数据库中获取” - 我得到预期的延迟(模拟数据库),然后:

在此输入图像描述

This all works as expected. 这一切都按预期工作。

The "parent" component is : “父”组件是:

//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);
  }
}

This is the Injected component : 这是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;

}

So where is the problem ? 那问题出在哪里?

As you can see , in the injected component I have : 如您所见,在注入的组件中,我有:

@Input
User:Person;

which means that I want the parent component to pass a Person object to each injection. 这意味着我希望parent组件将Person对象传递给每次注入。

In other words : 换一种说法 :

Question

Looking at the "after db stage" , How can I pass a customized person to each injection ? 看看“db 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` ???

    }
  })

}

Expected output : 预期产量:

在此输入图像描述

NB I don't want to use ngFor because I don't need to hold an Array at the back end. NB我不想使用ngFor因为我不需要在后端保持一个数组。 this is an app which injects new articles periodically.and I will be glad to know if there's a better way of doing it. 这是一个定期注入新文章的应用程序。我很高兴知道是否有更好的方法。

You can do it with the instance property of component ref like this: 您可以使用组件引用的instance属性执行此操作,如下所示:

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

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

    let ref = this.target.createComponent(compFactory);
    ref.instance.user = p;
}

-Fixed the @Input() binding, syntax was wrong. - @Input()绑定,语法错误。

-Added a safe-navigation operator ( ? ) for the template to do the null checks for the async input. - 为模板添加了一个安全导航操作符( ? ),以便对异步输入进行空检查。

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

use *ngFor and iterate through an array of Person, that way you can use the @Input. 使用* ngFor并遍历Person数组,这样就可以使用@Input。 You probably want something like 你可能想要这样的东西

<ul>
  <li *ngFor="let person of people">
    <test-component [User]=person></test-component>
  </li>
</ul>

add people: Person[] to your main component and when you fetch items 添加人物:Person []到您的主要组件以及何时获取物品

p.then(v=>{

for (let i =0;i<v;i++)
{
   let p = new Person();
   p.Name = "name"+i;
   p.Age = i;  
   people.push(p)
}
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM