【问题标题】:Get position X,Y from list from html从html的列表中获取位置X,Y
【发布时间】:2022-01-18 18:57:22
【问题描述】:

我有输入文本,用户可以搜索元素并且我有列表,我想在用户放置它时滚动到该列表中的元素,但我无法获取列表中特定元素的位置 X、Y ,这是我的代码

<input type="text" (change)="search(event)">
<div *ngFor="let item from list">
{{item.lib}}
</div>
search(event:any){
let itemSearch = event.target.value;
this.list = this.list.filter((val)=>{
if(val.lib.indexOf(itemSearch)>=0){
let scrollY= val.lib.indexOf(itemSearch);
if(scrollY !==-1){
document.querySelector('.scroll')?.scroll (0,Scroll);
}
}
)};
This.list;
}

【问题讨论】:

    标签: angular typescript arraylist scroll


    【解决方案1】:

    使用ViewChildren。如果你使用模板引用变量

    <div #divItem *ngFor="let item from list">
    {{item.lib}}
    </div>
    
    @ViewChildren('divItem') listDiv:QueryList<ElementRef>
    

    在你的函数搜索中

    //first We lookfor the index of the Array
    const index=this.list.findIndex(x=>indexOf(word)>=0)
    if (index>=0)
    {
       //we find in the QueryList the element that has the "index"
       const el=this.listDiv.find((_,i)=>i==index)
       console.log(el.nativeElement.getBoundingClientRect())
       //you can use also
       el.nativeElement.scrollIntoView()
    }
    

    注意:您也可以在输入中使用模板引用变量

    <input #input type="text" (input)="search(input.value)">
    
    search(word:string){
       ....
    }
    

    【讨论】:

    • 它不适用于@viewChildren 我有未定义的错误我尝试搜索以找到解决方案
    • 我用@ViewChildren 做,但它对位置不好,我为getBoundingClientRec() 滚动这个位置但不好。
    • 谢谢你
    • @Ines,请注意,我为数组和 QueryList 使用了相同的名称。错了,我刚刚更正了命名为listDivs和list
    • 是的,我明白了,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-08-02
    • 2012-02-15
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多