簡體   English   中英

Angular:將動態元素滾動到視圖中,僅知道其ID

[英]Angular: Scroll dynamic element into view knowing only its ID

我有一個動態列表,它以異步方式獲取其數據,並希望在加載列表時將特定元素滾動到視圖中。

該列表的構建類似於:

<div class="items" *ngFor="let item of functionThatGetsItems(); let i = index" [id]="'MyList' + i">
    <div class="title">
        {{ item.title }}
    </div>
    <div class="content">
        {{ item.content }}
    </div>
  </div>      

如您所見,這些項目的ID分配為簡單的基本字符串及其編號。 假設我要觸發滾動到MyList31 加載並呈現列表后,如何獲取具有此ID的元素並滾動到該元素?

我已經四處搜索並找到了你不應該這樣做的方法,以及如何使用ViewRef來做到這一點,但這些似乎不適用於動態元素,或者它們是什么? 我該怎么做?

這不是嚴格的角度,但你可以做document.querySelector('#MyList31').scrollIntoView()

參考https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

為了做到這個嚴格的角度,本文可以幫助您http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html

使用模板引用並調用本機scrollIntoView()方法。 在你的HTML中:

<h2 #scrollToMe>Hi there</h2>

在您的組件中:

@ViewChild('scrollToMe') scrollToMe: ElementRef;

...


this.scrollToMe.nativeElement.scrollIntoView({ behavior: 'smooth' })

behavior: 'smooth'動畫過渡。

您希望id位於ng-for創建的實際項目上,而不是ng-for本身。 當從組件將數據傳遞到列表時,這將消除對任何額外邏輯的需要。

 // inside ngAfterViewInit() to make sure the list items render or inside ngAfterViewChecked() if you are anticipating live data using @Inputs const itemToScrollTo = document.getElementById('item-' + id); // null check to ensure that the element actually exists if (itemToScrollTo) { itemToScrollTo.scrollIntoView(true); } 
 <div class="list" *ngFor="let item of functionThatGetsItems(); let i = index"> <div class="list-item" id="item-{{i}}"> <div class="title"> {{ item.title }} </div> <div class="content"> {{ item.content }} </div> </div> </div> 

我設法使用屬性綁定解決了這個問題。

首先,當我收到定義要滾動到哪個項目的參數時,我將其保存為組件屬性。

this.toScrollInto = Object.keys(params)[0];

然后,在構建它的ngFor內部,我綁定到它並利用短路來調用函數,如果有匹配。

<div class="items" *ngFor="let item of functionThatGetsItems(); let i = index" 
    #itemRef
    [class.scrolled]="i == this.toScrollInto && scrollIntoView(itemRef)">

    <div class="title">
        {{ item.title }}
    </div>
    <div class="content">
        {{ item.content }}
    </div>
  </div>  

然后,函數scrollIntoView(Element)使用提供的Angular引用處理滾動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM