首页 > 解决方案 > 如何获取 Angular 共享组件的节点索引?

问题描述

我有一个共享组件,我将使用它https://stackblitz.com/edit/angular-ivy-nveufn

我不会用循环克隆组件,我会根据需要将其粘贴到 html 文件中。有没有办法让共享组件知道它是哪个节点的索引号,而无需在其父容器中进行循环?

标签: angularloopscomponents

解决方案


您应该可以通过使用模板引用变量和ViewChild访问本机元素来做到这一点。从那里您可以检查子节点的索引以获取位置。

<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;
  }
}

推荐阅读