0

I have a shared component that I will use as such https://stackblitz.com/edit/angular-ivy-nveufn

I will not clone the component with a loop, I will paste it next to one another as needed in the html file. Is there a way for the shared component to know which node's index number it is, without doing a loop in its parent container?

1 Answers1

1

You should be able to do it by accessing the native element using a template reference variable and ViewChild. From there you can examine the index of the child nodes to get the position.

<div #thing>
   <div>hello</div>
   <div>world</div>
   <div>2.0</div>
</div>


import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  title = 'myproject';
  @ViewChild('thing',{ static: true }) thing: ElementRef;
  ngAfterContentInit(): void {
    let a = this.thing.nativeElement.childNodes;
  }
}
dvalentine314
  • 60
  • 1
  • 7
  • Hi, thanks for your response. This is done on the parent level right? I'm wondering if there's any way to do it in the child component so that the code doesn't need to be replicated when it's used in multiple similar pages. – threezerothree Oct 24 '20 at 02:23
  • oh. I mixed up what "shared component" meant, my bad. From what I can tell, it seems like you can only do it by passing it in using an input property. [https://stackoverflow.com/a/40831149/2079367](https://stackoverflow.com/a/40831149/2079367) I am guessing this limitation is probably by design. it provides better separation of concerns. – dvalentine314 Oct 25 '20 at 01:46
  • your initial solution might be the better way to go about then. thank you once again! – threezerothree Oct 25 '20 at 13:29