代码之家  ›  专栏  ›  技术社区  ›  MortenMoulder

根据条件设置ViewChild

  •  0
  • MortenMoulder  · 技术社区  · 6 年前

    scrollIntoView . 基本上,我的伪代码如下所示:

    if selected element is not visible
        call scrollIntoView on the element
    

    问题是,每次按下键盘(上下箭头)时,我都需要调用它。我试着通过了考试 $event 要查找上一个元素、下一个元素等等,只需调用 scrollIntoView() 在这方面,但我认为这不是一个好主意。它涉及大量递归(因为树视图是嵌套的),我的HTML永远不会改变(除非我也更新代码)。

    可以设定吗 ViewChild() this.selectedElement.nativeElement.scrollIntoView() 或者类似的。除非有更好的主意?

    1 回复  |  直到 6 年前
        1
  •  1
  •   user4676340 user4676340    6 年前

    @ViewChildren ,这基本上是几个 @ViewChild .

    This stackblitz 展示了如何使用它,正如您所看到的,它非常容易使用。

    import { Component, QueryList, ElementRef, ViewChildren } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `<hello name="{{ name }}"></hello>
    <div 
      *ngFor="let index of [1, 2, 3, 4, 5]" 
      (mouseover)="hovered(divs)"
      #divs>
      This is the div n° {{ index }}
    </div>`,
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
    
      @ViewChildren('divs') divs: QueryList<ElementRef<HTMLDivElement>>;
    
      name = 'Angular';
    
      hovered(div: HTMLDivElement) {
        // Getting from the query list
        const corresponding = this.divs.find(_div => _div.nativeElement === div).nativeElement;
    
        // they are the same
        console.log(corresponding);
        console.log(corresponding === div);
        console.log(div);
      }
    }
    
    推荐文章