【问题标题】:how to reload/refresh dynamically injected component Angular 6如何重新加载/刷新动态注入的组件Angular 6
【发布时间】:2019-06-12 18:28:37
【问题描述】:

我正在尝试根据用户在下拉列表中选择的值动态注入组件。

我的要求是,每当用户更改下拉列表的值并单击视图组件时,都会注入但如果用户更改下拉列表值并单击视图,则应重新渲染相同的注入组件,而是重新渲染一个新组件被注入。

我们有什么办法可以做到这一点。

注意:在下拉列表更改时,会调用服务并从服务器返回不同的数据。

Stackblitz 的问题:https://stackblitz.com/edit/angular-cszxfs?file=src%2Fapp%2Fapp.component.ts

提前致谢

【问题讨论】:

  • 什么是“刷新”组件?
  • @cgTag 我的意思是说组件应该用新数据重新渲染
  • @cgTag 编辑了我的帖子
  • 您必须使用带有可观察对象的服务并发出组件订阅的新值。更新组件的数据与使用组件工厂无关。由于组件不能具有输入绑定,因此您必须自己弄清楚如何向其发送数据。
  • 为什么需要根据droprown的值动态注入组件? ngIf 或 hide 属性不起作用?

标签: angular dynamic


【解决方案1】:
<div *ngIf="somecondition">
<app-componentOne></app-componentOne>
</div>

<div *ngIf="somecondition">
<app-componentTwo></app-componentTwo>
</div>

like that you can import more that one component on selection of dropdown in ng if just manage your condition if that is true accordingly component will display..

【讨论】:

  • 感谢您的回复,但这不是我要找的
【解决方案2】:

所以我首先要删除组件,然后将其添加回视图中:

这是我的代码:

 renderTreeListReport(element: string) {
   this.removeComponents();
   const component = resultComponent[element];
   const factory = this.resolver.resolveComponentFactory<any>(component);
   this.component = this.resultcontainer.createComponent(factory);
   this.components.push(this.component);//for tracking the components created
   this.component.instance.config = this.config;
   this.component.instance.pagingInfo = this.pageble;
 }


 public removeComponents() {
   const components = this.components;
   if (components.length > 0) {
     components.forEach(comp => {
       this.resultcontainer.remove(components[comp])
     })
   }
 }

【讨论】:

    猜你喜欢
    • 2019-01-25
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多