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

2024-03-01

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

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因为我不需要在后端保存数组。这是一个定期注入新文章的应用程序。我很高兴知道是否有更好的方法。


你可以用instance组件 ref 的属性如下:

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

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

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

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

-添加了安全导航操作员(?) 让模板对异步输入进行 null 检查。

固定插头:https://plnkr.co/edit/WgWFZQLxt9RFoZLR46HH?p=preview https://plnkr.co/edit/WgWFZQLxt9RFoZLR46HH?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐