如何在 Angular2 (ngx) 中通过 css 选择器找到元素?

How can I find an element by css selector in Angular2 (ngx)?

如何通过 css 选择器在整个文档中找到元素,而不仅仅是在 Angular2 (ngx) 的子元素中?

angular.element(element.getElementsByClassName("classname"));

确保您没有在 class 名称前使用句点 (.)。

首先您需要从 angular 核心导入 ElementRef, 然后你可以使用查询选择器方法来获取元素

import { ElementRef,OnInit} from '@angular/core';
     element;

constructor( private el: ElementRef) {}
ngOnInit() {
    this.HTMLElement: HTMLImageElement = this.el.nativeElement.querySelector(`#selector`);
  }

ElementRef and HTMLElement

上查看这些文档

来自 angular 文档的警告

Use this API as the last resort when direct access to DOM is needed. Use templating and data-binding provided by Angular instead. Alternatively you can take a look at Renderer2 which provides API that can safely be used even when direct access to native elements is not supported.

Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker.