【问题标题】:How to get the node's index for an Angular shared component?如何获取 Angular 共享组件的节点索引?
【发布时间】:2020-10-24 00:52:27
【问题描述】:

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

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

【问题讨论】:

    标签: angular loops components


    【解决方案1】:

    您应该能够通过使用模板引用变量和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;
      }
    }
    

    【讨论】:

    • 您好,感谢您的回复。这是在父级别上完成的,对吗?我想知道在子组件中是否有任何方法可以在多个类似页面中使用时不需要复制代码。
    • 哦。我混淆了“共享组件”的含义,我的错。据我所知,您似乎只能通过使用输入属性传递它来做到这一点。 https://stackoverflow.com/a/40831149/2079367 我猜这个限制可能是设计使然。它提供了更好的关注点分离。
    • 您最初的解决方案可能是更好的解决方案。再次感谢您!
    猜你喜欢
    • 2013-05-02
    • 2011-08-20
    • 1970-01-01
    • 2018-03-30
    • 2018-12-12
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多