2016-05-15 24 views
2

我的應用程序將顯示消息列表(帶滾動)。當用戶添加新消息時,該頁面需要滾動到消息列表的底部。在新消息添加到消息列表後立即調用scrollToBottom()是否正確?或者它會給時間問題?該視圖是否已更新(包含新消息),這樣scrollHeight會正確嗎?或者用其他方式來形成我的問題:是否有一種方法可以知道/確保在模型更改時視圖完全更新。在Angular2中查看完全更新時調用函數

視圖(的messaging.html):

<div class=」height: 100%; scroll: auto」> 
    <div class="message" *ngFor="#message of messages"> 
    ... 
    </div> 
</div 

組件:

import {Component, ViewChild, ElementRef} from 'angular2/core'; 
import {CORE_DIRECTIVES} from 'angular2/common'; 

@Component({ 
    selector: 'messaging', 
    templateUrl: './messaging.html', 
    styleUrls: ['./messaging.css'], 
    directives: [CORE_DIRECTIVES] 
}) 
export class Messaging { 
    private messages:Message[] = []; 

    @ViewChild('messagingscroll') private messageScroll: ElementRef; 

    constructor() { 
    } 

    sendMessage(message:string, element) { 
    let msg:Message = new Message(message); 

    // Add msg 
    this.messages.push(msg); 

    // Scroll to bottom 
    this.scrollToBottom(); 

    // Set back empty 
    element.value = ''; 
    } 

    scrollToBottom(): void { 
    this.messageScroll.nativeElement.scrollTop = this.messageScroll.nativeElement.scrollHeight; 
    } 
} 

回答

3

如果你想調用函數時,你的看法是完全負載比你可以調用angular2的默認生命週期掛鉤即ngAfterViewinit()

參見此處瞭解更多信息https://angular.io/docs/ts/latest/api/core/AfterViewInit-interface.html

根據官員

實現此接口以在組件的視圖已完全初始化時得到通知。

由於您需要每次查看更改後都必須調用函數,因此您可以使用ngAfterViewchecked

實施此接口以在每次檢查組件視圖後收到通知。

多看這裏https://angular.io/docs/ts/latest/api/core/AfterViewChecked-interface.html

+1

ngAfterViewInit()將只在啓動/初始化時調用。所以不是在添加新消息之後。 但你的答案我發現,ngAfterViewChecked,我認爲這可能是解決方案? – user2276975

+0

是啊有幾個生命週期的觀點,你可以在這裏查看https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html –