ElementRef
- 获取视图层的dom元素,借助Augular提供的依赖注入机制,轻松的访问到dom元素
定义
/**
* A wrapper around a native element inside of a View.
*
* An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
* element.
*
* @security Permitting direct access to the DOM can make your application more vulnerable to
* XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the
* [Security Guide](<https://g.co/ng/security>).
*
* @publicApi
*/
export declare class ElementRef<T = any> {
/**
* The underlying native element or `null` if direct access to native elements is not supported
* (e.g. when the application runs in a web worker).
*
* <div class="callout is-critical">
* <header>Use with caution</header>
* <p>
* 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 {@link
* Renderer2}
* which provides API that can safely be used even when direct access to native elements is not
* supported.
* </p>
* <p>
* 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.
* </p>
* </div>
*
*/
nativeElement: T;
constructor(nativeElement: T);
}
使用
<div>我改改</div>
import { AfterViewInit, Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less'],
})
export class AppComponent implements AfterViewInit{
title = 'ng-study';
constructor(private elementRef: ElementRef) {}
// 模板中的元素已创建完成
ngAfterViewInit() {
console.dir(this.elementRef.nativeElement.querySelector('div'));
}
}
|