如何从ViewContainerRef.get获取动态创建的组件的Component实例

问题描述

我要完成的工作总结

  • 动态地将组件添加ViewContainerRef(完成)
  • 使用属性(完成)初始化这些动态组件
  • 获得对动态创建的Component实例的访问权,以便我可以根据是什么来做出决定。

问题

  • 动态添加组件时,会将它们添加ViewContainerRef
  • ViewContainerRef提供了返回get(index)方法,例如ViewRef
  • ViewRefComponent实例似乎没有任何关系,这对于获取所需数据来说是一个挑战

Here is a Stackblitz Link,下面显示工作代码(用于动态创建组件)

appComponent首先使用ComponentFactoryResolver创建一些组件,然后将它们添加到模板中定义的ViewChild中。每个DynamicComponent都使用一个id属性值进行初始化,我们将在创建后尝试引用该属性

@Component({
  selector: "my-app",template: `
    <h3>Retrieving Component Reference for Dyamic Compnents</h3>
    <button (click)="getCompRef()">Get References</button>
    <div>
      <ng-container #childCont></ng-container>
    </div>
    <div>
      <small>List out the Ids from the dynamic components</small> <br />
      {{ createdItemIds | json }}
    </div>
  `,styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
  @ViewChild("childCont",{ read: ViewContainerRef })
  childCont: ViewContainerRef;

  createdItemIds: string[] = [];

  itemLimit = 5;

  constructor(
    private fr: ComponentFactoryResolver,private cdr: ChangeDetectorRef
  ) {}

  ngAfterViewInit(): void {
    for (let i = 0; i < this.itemLimit; i++) {
      const factory = this.fr.resolveComponentFactory(DynamicComponent);
      const compRef = this.childCont.createComponent(factory,i);
      // Set the id of the instance so that we can use it later
      compRef.instance.id = i + 1;
      this.cdr.detectChanges();
    }
  }
  ...
}

添加DynamicComponent非常简单。为简化起见,它仅包含一个我们试图获取id属性

@Component({
  selector: "dynamic-component",template: `
    <div>Dynamic Component: {{ id }}</div>
  `,styles: [``]
  ]
})
export class DynamicComponent {
  id: number;
} 

到目前为止一切都很好。

  • 组件是动态创建的
  • 使用ID初始化组件实例,通过显示在UI中的胖图标我们可以看到它

问题来自尝试从DynamicallyCreated组件中检索ID属性

AppComponent中,当用户单击按钮时,将调用getCompRef()方法并遍历childCont (ViewContainerRef)的每个子对象

getCompRef(): void {
  for (let i = 0; i < this.itemLimit; i++) {
    const viewRef = this.childCont.get(i);
    // How do I get at the instance of the view  in order to obtain id?
    // the view Ref doesn't provide access to the instance
    // console.log(viewRef);
  }
}

然而,从ViewRef返回的ViewContainerRef.get()ChangeDetectoreRef的子类,并且不包含对所讨论实例的任何引用。

在对此问题进行研究时,它尝试使用ViewChildren获取正在创建的列表组件,但这由于诸如此类的问题而无法正常工作

  • https://github.com/angular/angular/issues/8785
  • 或示例假定ViewChildren selector中使用的指令是针对已在模板中预定义的组件的。
  • 对于一些希望拥有Component.instance的人获得ViewRef的人,我看到了很多问题,但这在这种情况下没有帮助。

最终我的问题是,

  • 有没有一种简单的方法可以从我所缺少的ViewRef获取Component实例

感谢您的帮助。

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)