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

如何解决如何从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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?