uksz
uksz

Reputation: 18699

How to access parent HTML element from component?

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?

Upvotes: 40

Views: 71611

Answers (2)

Anton Pegov
Anton Pegov

Reputation: 1474

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')
}

Upvotes: 9

michael
michael

Reputation: 16341

Inject the element itself:

constructor(private elRef: ElementRef){}

access the native elements parent:

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

Upvotes: 59

Related Questions