我的應用程序將顯示消息列表(帶滾動)。當用戶添加新消息時,該頁面需要滾動到消息列表的底部。在新消息添加到消息列表後立即調用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;
}
}
ngAfterViewInit()將只在啓動/初始化時調用。所以不是在添加新消息之後。 但你的答案我發現,ngAfterViewChecked,我認爲這可能是解決方案? – user2276975
是啊有幾個生命週期的觀點,你可以在這裏查看https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html –