微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

Plunker

enter image description here

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

enter image description here

如果我在文本中设置“3”并单击“从数据库获取” – 我得到预期的延迟(模拟数据库),然后:

enter image description here

这一切都按预期工作.

“父”组件是:

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

这是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;

}

那问题出在哪里?

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

@Input
User:Person;

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

换一种说法 :

看看“db db stage”之后,我怎样才能将定制人员传递给每次注射?

  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` ???

    }
  })

}

预期产量:

enter image description here

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

解决方法:

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

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

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

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

– 修复@input()绑定,语法错误.

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

固定式吸油烟机:https://plnkr.co/edit/WgWFZQLxt9RFoZLR46HH?p=preview

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐