Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent HTML element from component?

Tags:

angular

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

like image 618
uksz Avatar asked Jul 22 '16 09:07

uksz


2 Answers

Inject the element itself:

constructor(private elRef: ElementRef){}

access the native elements parent:

ngOnInit() {
  console.log(this.elRef.nativeElement.parentElement);
}
like image 58
michael Avatar answered Oct 04 '22 22:10

michael


You can access closest parent DOM element by looking up with this.elRef.closest and some selector that matches that parent

constructor(private elRef: ElementRef){}

ngOnInit() {
   const parentElement = this.elRef.closest('.parent-element-class')
}
like image 39
Anton Pegov Avatar answered Oct 04 '22 21:10

Anton Pegov