angular - Angular 6:给定 ElementRef,我可以得到 ViewContainerRef
问题描述
模板
<div my-directive></div>
指示
constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {}
useService() {
this.svc.doWork(vc, el);
}
所以服务需要 aViewContainerRef
和 a ElementRef
。我必须两个都通过吗?有没有办法从元素 ref 派生视图容器?如果是这样,我只需要传递ElementRef
给服务,它就会从中获取视图容器。
或者,可以ElementRef
从ViewContainerRef
? 似乎不可能,因为我假设一个视图容器可以有多个元素。
解决方案
您可以使用视图中的元素引用。它们都引用相同的 DOM 元素。
constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {
console.log(vc.element.nativeElement === el.nativeElement);
// prints true
this.svc.doWork(vc, vc.element);
}
推荐阅读
- typescript - 在 Angular5 中获取本地存储对象函数时出错
- sapui5 - SAPUI5 FileUploader 最大文件大小警报
- python - 分组数据帧中的有效循环以访问当前和先前索引的值(并计算差异)
- ruby-on-rails - Rails 解析 csv 分隔符 ¦
- match - 如何正确验证json中的新字段
- authentication - 如何在 Apache Airflow 中激活身份验证
- java - 按顺序查找并获取 2 个单击按钮的 id
- openmp - Blitz++、犰狳和 OpenMP 非常慢
- angular - 代理配置在角度 6 中不起作用
- visual-studio-code - 如何轻松地将 Visual Studio Code 工作区移动到新位置?