在我的Angular 7应用程序中,树视图中有超过5000个元素。我需要访问已经选择的DOM元素,所以我可以使用scrollIntoView之类的东西。基本上,我的伪代码将如下所示:
if selected element is not visible
call scrollIntoView on the element问题是,我需要在每次按下键盘时调用这个函数(向上和向下箭头)。我尝试过传入$event来查找前一个元素、下一个元素等等,所以我可以简单地在该元素上调用scrollIntoView(),但我认为这不是一个好主意。它涉及到很多递归(因为树视图是嵌套的),并且我的HTML永远不会改变(除非我也更新了代码)。
可以根据条件设置ViewChild()吗?这样我就可以简单地做this.selectedElement.nativeElement.scrollIntoView()或类似的事情了。除非有更好的主意?
发布于 2018-11-06 17:18:49
这不是很清楚,但是如果我没弄错的话,你可以使用@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);
}
}https://stackoverflow.com/questions/53168778
复制相似问题