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

标签 html angular css-selectors angular5 angular2-services

如何通过 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/

相关文章:

javascript - SVG 和 JavaScript - 动画 SVG 文件对象不起作用?

javascript - Mousedown 和 mouseup 同时以 Angular 触发

html - 浏览器忽略 HTML 元素的 CSS 选择器

html - 使用单页导航突出显示事件选项卡

python - 如何在自定义模板标签中传递 url 标签?

css - 我可以使用其所有 css 功能制作一个与其普通 View 相同的可打印网页吗?

javascript - 如何删除背景图像中的这个顶部空间?

angular - 类型 'number' 的参数不可分配给类型 'string' 的形参

angular - 无法绑定(bind)到 'aria-valuenow',因为它不是 'div' 的已知属性

IE7 表格中的 CSS 子选择器