Identifying Angular component instances by a unique ID

Viewed 2631

I'm working on an Angular application where I created a component called TripSummaryComponent that I'm using for showing trips informations this way :

<div *ngFor="let trip of trips">
    <trip-summary [trip]="trip"></trip-summary>
</div>

enter image description here Now my need is: how to identify each instance of TripSummaryComponent by a unique id after it's generated in the DOM.

Thank's in advance for helping.

2 Answers

I would not recommend passing an ID via an input to the child component. Why not directly creating one in the child component itself via an UUID generator (which you need to provide with a third party library, e.g. uuid generator):

Component

readonly id: string;

ngOnInit() {
  this.id = uuid.v4();
}

Template

<div [attr.id]="id">
  <!-- rest of the template -->
</div>

I have an idea: Of course I really don't recommend to this. But It can be done.

Use ViewChildren and QueryList

Identify each instance of TripSummaryComponent

Add an idGenerator() that always return unique id

by a unique id

Inside ngAfterViewInit()

after it's generated in the DOM.

Requirements

Add id input to trip-summary component

@Input() trip
@Input() id

Get trip-summary component references

Use ViewChildren and QueryList to have all components refences.

@ViewChildren(TestComponent) testQueryList: QueryList<TestComponent>;

  trip = [
    { id: "1", name: "one" },
    { id: "2", name: "two" },
    { id: "3", name: "three" }
  ];

  ngAfterViewInit() {
    this.testQueryList.forEach(component => console.log(component));
    this.cd.detectChanges();
  }

Add unique id to trip-summary components inside ngAfterViewInit

ngAfterViewInit() {
  this.testQueryList.forEach((component, index) => component.id = this.generateUniqueId());
}

private generateUniqueId(): string {
  return 'here should return unique id'
}

Result

Each instance of components has unique id

Working example: https://stackblitz.com/edit/angular-ivy-r6qlkm?file=src%2Fapp%2Fapp.component.ts

Related