我使用Angular 9并使用ViewChild和ViewChildren来选择我的HTML文件中存在的元素。这两个函数中有支持类选择器的吗?据我所知,它们只适用于身份证。
@ViewChild('.foo') Foo: ElementRef;任何替代方法也是好的,只是在函数执行期间,我希望能够访问所有的'Foo‘对象。
https://angular.io/api/core/ViewChild
https://angular.io/api/core/ViewChildren
谢谢!
发布于 2020-07-18 02:02:25
不,ViewChild不支持类选择器。要获取一个HTML元素,可以使用template reference variable,如下所示:
<div #refElement> ... </div> // # refElement is a template reference variable.ts
@ViewChild('refElement') el: ElementRef;
// viewchild instance will be available in or after ngAfterviewInit life cycle hook
ngAfterViewInit(){
console.log(this.el.nativeElement);
}发布于 2020-07-18 02:09:56
ViewChild或ViewChildren仅适用于references(e.xhtml格式的#element )。如果你想按类选择,你可以使用ElementRef。ElementRef将允许您访问组件的模板。因此,在获得组件模板作为html元素后,您可以使用原生javascript函数,如getElementsByClassName。
constructor(private elementRef: ElementRef) {}
...
this.elementRef.nativeElement.getElementsByClassName('foo')https://stackoverflow.com/questions/62959389
复制相似问题