📅  最后修改于: 2023-12-03 15:29:23.429000             🧑  作者: Mango
In Angular, the ElementRef
class provides access to the underlying HTML element of a component, directive or a DOM element in a template. The ElementRef
allows us to perform operations on the HTML element such as getting or setting its attributes, listening to events, modifying its styles, and much more.
Sometimes, we may want to access the parent element of an ElementRef
object to perform certain operations or get some information about the parent element. In this article, we’ll see how to access the parent element of an ElementRef
object and perform some operations on it in TypeScript.
To access the parent element of an ElementRef
object, we need to use the nativeElement
property of the ElementRef
object. This property returns the underlying native HTML element, which we can then use to access its parentElement
property.
Here’s an example of accessing the parent element of an ElementRef
object:
import { Component, ElementRef, OnInit } from '@angular/core';
@Component({
selector: 'app-my-component',
template: '<div id="my-div" class="container"></div>'
})
export class MyComponent implements OnInit {
constructor(private elRef: ElementRef) {}
ngOnInit() {
const myDiv = this.elRef.nativeElement.parentElement;
console.log(myDiv); // Output: <body>…</body>
}
}
In the above example, we have a simple component that has a <div>
element. We access this element in the ngOnInit()
method of the component using the ElementRef
and get its parent element using the parentElement
property of the nativeElement
.
Here, we’re logging the parent element to the console, which is the <body>
element of our HTML page.
Once we have access to the parent element using the ElementRef
, we can perform any operations that we want on it.
Here’s an example of setting the background color of the parent element using the style
property of the parent element:
import { Component, ElementRef, OnInit } from '@angular/core';
@Component({
selector: 'app-my-component',
template: '<div id="my-div" class="container"></div>'
})
export class MyComponent implements OnInit {
constructor(private elRef: ElementRef) {}
ngOnInit() {
const myDiv = this.elRef.nativeElement.parentElement;
myDiv.style.backgroundColor = 'red';
}
}
In the above example, we’ve set the background color of the parent element of the <div>
to red by accessing the parent element using the ElementRef
, and then setting its background color using the style
property.
In conclusion, we have seen how to access the parent element of an ElementRef
object and perform some operations on it in TypeScript. The nativeElement
property of the ElementRef
object provides us with the underlying HTML element, which can then be used to access the parent element or perform operations on it.
By understanding how to use the ElementRef
and nativeElement
properties, we can easily manipulate the DOM elements in our Angular applications, making them more dynamic and engaging for the user.