Angular v4.3.3:除了@ViewChild 之外,还有其他方法可以通过模板ID 访问模板元素吗?
Angular v4.3.3: Is there an alternative to accessing template elements by template ID other than @ViewChild?
在早期版本中,这是使用@ViewChild 获取元素引用的可接受方式。
@ViewChild('#templateId') elementName: ElementRef;
从现在看来,这不再是一个可行的选择,因为@ViewChild 正在寻找要注入的特定组件。
我尝试将 ElementRef
注入到构造函数中,但我尝试处理的元素引用深深地嵌套在模板中。也许这是最好的解决方案,但如果可能的话,我正在寻找更好的解决方案。
您仍然可以使用 @ViewChild
装饰器从视图模板中查询元素。例如:
@ViewChild('templateId')
public myElement: ElementRef<any>;
...
<div #templateId></div>
将获得 div
和 #templateId
的 ElementRef。但请记住,只有一个带有 #templateId
的元素才能通过 ViewChild
查询它。而且它仅在 ngAfterViewInit
生命周期挂钩之后可用。
在早期版本中,这是使用@ViewChild 获取元素引用的可接受方式。
@ViewChild('#templateId') elementName: ElementRef;
从现在看来,这不再是一个可行的选择,因为@ViewChild 正在寻找要注入的特定组件。
我尝试将 ElementRef
注入到构造函数中,但我尝试处理的元素引用深深地嵌套在模板中。也许这是最好的解决方案,但如果可能的话,我正在寻找更好的解决方案。
您仍然可以使用 @ViewChild
装饰器从视图模板中查询元素。例如:
@ViewChild('templateId')
public myElement: ElementRef<any>;
...
<div #templateId></div>
将获得 div
和 #templateId
的 ElementRef。但请记住,只有一个带有 #templateId
的元素才能通过 ViewChild
查询它。而且它仅在 ngAfterViewInit
生命周期挂钩之后可用。