【问题标题】:ViewChild/ViewChildren and class selector in AngularAngular 中的 ViewChild/ViewChildren 和类选择器
【发布时间】:2021-06-08 03:27:45
【问题描述】:

我使用 Angular 9 并使用 ViewChildViewChildren 来选择我的 HTML 文件中存在的元素。这两个函数中的任何一个都支持类选择器吗?据我所知,它们仅适用于 ID。

@ViewChild('.foo') Foo: ElementRef;

任何替代方案也很好,只是在执行函数期间我想访问所有“Foo”对象。

https://angular.io/api/core/ViewChild

https://angular.io/api/core/ViewChildren

谢谢!

【问题讨论】:

  • 你想达到什么目的?
  • 我想通过类选择器获取HTML元素SnativeElement。我认为 ViewChild/ViewChildren 可以帮助我

标签: angular


【解决方案1】:

ViewChild 或 ViewChildren 仅适用于 references(例如 html 中的 #element)。 如果你想按班级选择,你可以使用ElementRefElementRef 将允许您访问组件的模板。 因此,在将组件模板作为 html 元素后,您可以使用像 getElementsByClassName 这样的原生 javascript 函数。

constructor(private elementRef: ElementRef) {}
...
this.elementRef.nativeElement.getElementsByClassName('foo')

【讨论】:

  • 应该带点:this.elementRef.nativeElement.getElementsByClassName('foo')
【解决方案2】:

不,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); 
 }

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2019-06-20
    • 2022-11-21
    • 1970-01-01
    • 2018-08-16
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多