Javascript Angular 2.x 选择 DOM 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34432980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2.x selecting DOM element
提问by Arūnas Smaliukas
I know it should be easy but angular 2.0 has no many examples yet..
我知道这应该很容易,但 angular 2.0 还没有很多例子。
In one of my components in some case I need to add class on my body tag. But my application is bootstrapped deeper than body, so I need something like
在某些情况下,在我的一个组件中,我需要在 body 标签上添加类。但是我的应用程序比 body 更深,所以我需要类似的东西
angular.element('body').addClass('fixed');
but in Angular 2.0..
但在 Angular 2.0..
BTW, I know I can somehow bootstrap my application to include body
tag, but I think in some other cases I would need to select some elements anyway, so I need a solution how to do this simple task - "select element and add class to it"
顺便说一句,我知道我可以以某种方式引导我的应用程序以包含body
标签,但我认为在其他一些情况下我无论如何都需要选择一些元素,所以我需要一个解决方案来完成这个简单的任务 - “选择元素并为其添加类”
采纳答案by Günter Z?chbauer
Update
更新
I'm not sure if DOM
is actually still supported in RC. The related statements aren't very clear. Something like
我不确定DOM
RC是否仍然支持。相关的说法不是很清楚。就像是
DOM
is only for internal use. Either access the DOM directly or use a custom renderer.
DOM
仅供内部使用。直接访问 DOM 或使用自定义渲染器。
I haven't see how a custom renderer might be implemented or how to provide an implementation depending on the current platform (webworker, server, DOM thread).
我还没有看到如何实现自定义渲染器或如何根据当前平台(webworker、服务器、DOM 线程)提供实现。
UpdateThis seems to be the Angular2 way
更新这似乎是 Angular2 的方式
import { DOM } from 'angular2/src/platform/dom/dom_adapter';
DOM.addClass(DOM.query("body"), 'fixed');
Import from .../src/...
at your own risk. .../src/...
is considered private implementation and you can't expect any guarantees that the API won't change without notice.
进口自.../src/...
担风险。.../src/...
被视为私有实现,您不能指望任何保证 API 不会在没有通知的情况下更改。
I tried it in Dart and it works fine (not sure if the TS import above is correct though). In Dart DOM
is exported by package:angular2/angular2.dart
我在 Dart 中尝试过,效果很好(但不确定上面的 TS 导入是否正确)。在 DartDOM
中由package:angular2/angular2.dart
Original
原来的
If you want to access a DOM element that's outside of your Angular application root, just use document.querySelector()
, no need to involve Angular.
如果要访问 Angular 应用程序根目录之外的 DOM 元素,只需使用document.querySelector()
,无需涉及 Angular。
回答by JDTLH9
As of Angular2 Version 2.0.0-beta.17.
从 Angular2 版本 2.0.0-beta.17 开始。
Attribute Directivesin Angular2 will do this for you nicely.
Angular2 中的属性指令会很好地为你做这件事。
Please see this plunkwritten in TypeScript. This does what you want nicely.
请参阅本普拉克写的打字稿。这很好地完成了你想要的。
The directive file my-highlight.ts
has the line:
指令文件my-highlight.ts
有一行:
this.renderer.setElementClass(this.element, "red", true);
This sets the CSS class on the element.
这会在元素上设置 CSS 类。
While template.html
has the actual element which is decorated with the directive [myHighlight]
:
虽然template.html
具有用指令装饰的实际元素[myHighlight]
:
<p [myHighlight]>Mouseover to highlight me!</p>
This, to me, provides the least hack-ish answer to the question without any dependency on jqLite.
对我来说,这为这个问题提供了最少的 hack-ish 答案,而不依赖于 jqLite。
回答by Stefan Rein
As of angular 2.4
you should inject the DOCUMENT
and don't interact with any adapter:
截至angular 2.4
您应该注入DOCUMENT
并且不与任何适配器交互:
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Component({})
export class MyClass {
constructor (@Inject(DOCUMENT) private document) { }
doSomething() {
this.document.someMethodOfDocument();
}
}
Further reading: https://github.com/angular/angular/issues/8509
回答by xameeramir
DOM Manipulation in Angular 2 / 4 app
Angular 2 / 4 应用程序中的 DOM 操作
To manipulate the DOM in Angular 2/4 apps, we need to implement
the method ngAfterViewInit()
of AfterViewInit
. The method ngAfterViewInit()
is called when the bindings of the children directives have been checked for the first time. In other words, whenthe view is initially rendered.
为了操纵角2/4应用的DOM,我们需要implement
方法ngAfterViewInit()
的AfterViewInit
。ngAfterViewInit()
当第一次检查子指令的绑定时调用该方法。换句话说,当最初呈现视图时。
The @ViewChild
provides access to nativeElement
. It is recommended to not access nativeElement
inside the ngAfterViewInit()
because it is not browser safe. Also, it's not supported by web workers. Web workers will never know when the DOM updates.
在@ViewChild
提供了访问nativeElement
。建议不要访问nativeElement
里面,ngAfterViewInit()
因为它不是浏览器安全的。此外,它不受网络工作者支持。Web Worker 永远不会知道 DOM 何时更新。
The right way is to use renderer
. The renderer needs to be injected to the component constructor. We need to provide an id
reference to the HTML
element on the view something like this:
正确的方法是使用renderer
. 渲染器需要注入到组件构造函数中。我们需要提供对视图上元素的id
引用,HTML
如下所示:
<p #p1></p>
<p #p1></p>
It shall be accessed by the corresponding coponent .ts
file, something like this:
它应由相应的组件.ts
文件访问,如下所示:
export class SampleComponent implements AfterViewInit {
@ViewChild("p1") p1;
constructor(private renderer: Renderer2) //Renderer set to be depreciated soon
{ }
ngAfterViewInit() {
//recommended DOM manipulation approach
this.renderer.setStyle(this.p1.nativeElement, //setElementStyle for soon to be depreciate Renderer
'color',
'red');
//not recommended DOM manipulation approach
//this.p1.nativeElement.style = "color:blue;";
}
}
回答by TGH
I don't recommend direct DOM access from Angular, but you have a DOM hook via the ElementRef of your component. Once you have access to it you can use it directly or via jquery or any other DOM manipulation technique. I have included an example of how to use jquery to run general queries. If you are always going for the body tag you don't really need ElementRef, but it's useful for something that is relative to the root of the component.
我不建议从 Angular 直接访问 DOM,但是您通过组件的 ElementRef 有一个 DOM 钩子。一旦您可以访问它,您就可以直接或通过 jquery 或任何其他 DOM 操作技术使用它。我已经包含了一个如何使用 jquery 运行常规查询的示例。如果您总是使用 body 标记,则您实际上并不需要 ElementRef,但它对于与组件根相关的内容很有用。
import {Component, ElementRef, OnInit} from '@angular/core';
declare var jQuery:any;
@Component({
selector: 'jquery-integration',
templateUrl: './components/jquery-integration/jquery-integration.html'
})
export class JqueryIntegration implements OnInit {
elementRef: ElementRef;
constructor(private elementRef: ElementRef) {
}
ngOnInit() {
jQuery(this.elementRef.nativeElement).find('.moving-box').draggable({containment:'#draggable-parent'});
}
}
More info here: http://www.syntaxsuccess.com/viewarticle/using-jquery-with-angular-2.0
更多信息在这里:http: //www.syntaxsuccess.com/viewarticle/using-jquery-with-angular-2.0
Demo: http://www.syntaxsuccess.com/angular-2-samples/#/demo/jquery
演示:http: //www.syntaxsuccess.com/angular-2-samples/#/demo/jquery