How to access the parent HTML element from a component?

As in the question - I have a child component, and I would like to know what the width of the parent element is. How can i do this?

+9
source share
3 answers

Enter the element itself:

constructor(private elRef: ElementRef){}

access parent elements:

ngOnInit() {
  console.log(this.elRef.nativeElement.parentElement);
}
+17
source

The Angular2 manual contains an entire chapter on component relationships to describe such scenarios. https://angular.io/docs/ts/latest/cookbook/component-communication.html

+3
source

You can access the nearest parent DOM element by looking at this.elRef.closestsome selectors corresponding to this parent element.

constructor(private elRef: ElementRef){}

ngOnInit() {
   const parentElement = this.elRef.closest('.parent-element-class')
}
0
source

Source: https://habr.com/ru/post/1648757/


All Articles