ElementRef is 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.
Constructor
-
constructor(nativeElement: T)
Here nativeElement is parameter. The underlying
native element or null if direct access to native elements is not supported.
Security
risk on ElementRef -
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, seethe Security Guide.
class ElementRef<T> {
constructor(nativeElement: T)
nativeElement: T
}
Example
,
import { AfterContentInit, Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>My Angular App</h1>
<pre> <code>{{ name }}</code> </pre>
`
})
export class AppComponent implements AfterContentInit {
name: string;
constructor(private elementRef: ElementRef) { }
ngAfterContentInit() {
const tmpEle = document.createElement('div');
const el = this.elementRef.nativeElement.cloneNode(true);
tmpEle.appendChild(el);
this.name = tmpEle.innerHTML;
}
}