如何通过 css 选择器在整个文档中找到元素,而不仅仅是在 Angular2 (ngx) 的子元素中?
最佳答案
首先,您需要从 Angular Core 导入 ElementRef
,
然后你可以使用查询选择器方法来获取元素
import { ElementRef,OnInit} from '@angular/core';
element;
constructor( private el: ElementRef) {}
ngOnInit() {
this.HTMLElement: HTMLImageElement = this.el.nativeElement.querySelector(`#selector`);
}
在 ElementRef 上查看这些文档和 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.
关于html - 如何在 Angular2 (ngx) 中通过 css 选择器找到元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49530213/