【发布时间】:2020-10-24 00:52:27
【问题描述】:
我有一个共享组件,我将使用它https://stackblitz.com/edit/angular-ivy-nveufn
我不会用循环克隆组件,我会根据需要将其粘贴到 html 文件中。有没有办法让共享组件知道它是哪个节点的索引号,而无需在其父容器中进行循环?
【问题讨论】:
标签: angular loops components
我有一个共享组件,我将使用它https://stackblitz.com/edit/angular-ivy-nveufn
我不会用循环克隆组件,我会根据需要将其粘贴到 html 文件中。有没有办法让共享组件知道它是哪个节点的索引号,而无需在其父容器中进行循环?
【问题讨论】:
标签: angular loops components
您应该能够通过使用模板引用变量和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;
}
}
【讨论】: