通过唯一 ID 识别 Angular 个组件实例

Identifying Angular component instances by a unique ID

我正在开发一个 Angular 应用程序,我在其中创建了一个名为 TripSummaryComponent 的组件,我用它来以这种方式显示旅行信息:

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

现在我的需求是:如何在 DOM.

中生成每个 TripSummaryComponent 实例后通过唯一 id 来识别它

在此先感谢您的帮助。

我有一个想法:当然我真的不推荐这个。但这是可以做到的。

使用ViewChildrenQueryList

Identify each instance of TripSummaryComponent

添加一个始终 return 唯一 ID

idGenerator()

by a unique id

在 ngAfterViewInit() 内部

after it's generated in the DOM.

要求

id 输入添加到 trip-summary 组件

@Input() trip
@Input() id

获取trip-summary个组件引用

使用 ViewChildrenQueryList 来引用所有组件。

@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();
  }

在 ngAfterViewInit

中向 trip-summary 组件添加唯一 ID
ngAfterViewInit() {
  this.testQueryList.forEach((component, index) => component.id = this.generateUniqueId());
}

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

结果

每个组件实例都有唯一的 id

工作示例https://stackblitz.com/edit/angular-ivy-r6qlkm?file=src%2Fapp%2Fapp.component.ts

我不建议通过输入向子组件传递 ID。为什么不通过 UUID 生成器直接在子组件本身中创建一个(您需要提供第三方库,例如 uuid generator):

组件

readonly id: string;

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

模板

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