Get unique instance of Custom Component


#1

I have a component (a parallax header) that I am importing into certain pages in an Ionic4 app.
In order for the parallax to work, I need to reference an element inside of it.
Which works fine until I have more than one page that has used the custom component, at which point it access the First instance of the component the app produced.
So, page2 references page1’s component.

My work around is to put the component inside a div with a unique element ID specific to that page.
I can then reference it like so:

this.header = document.getElementById('header_contact').getElementsByClassName('header-image')[0];

Here is the markup:
<custom-header id="header_contact" [header]="header_data"><custom-header>

The page is a Contact page and header-image is the element inside the component I need to access.
This works but seems unnecessary and I am wondering if any other options come to mind?

have the custom component imported via a components.module.

( I have had no luck making this work as a directive in Ionic 4 )

My current options are

  1. Use as above with the element ID.
  2. Use a service to reference the current working instance of the custom component.
  3. Iterate through the getElementsByClassName list and look for its ‘presence’ in the view …?
  4. Destroy each instance of the custom component on page leave.

#2

This sounds like exactly the sort of problem that @ViewChild was designed to address. Did you try that?


#3

I did try @ViewChild with no luck - But gave it another go and had success:

@ViewChild(‘customheader’, { read: ElementRef }) customheader: any;
@ViewChild(‘main-content’, { read: ElementRef }) maincontent: any;

ngOnInit() {
    this.header = this.customheader['nativeElement'].getElementsByClassName('header-image')[0];
    this.headerHeight = this.header.clientHeight;
}

Thanks for the push back in the right direction!