我一般都是Angular2和Angular的新手,并且在组件的数据发生更改后更新dom后尝试获取一些jQuery.jQuery需要计算元素的高度,所以我不能完全使用数据.不幸的是,看起来onAllChangesDone只在数据更改后触发,而不是dom.
Art*_*tod 60
我发现生命周期钩子ngAfterViewChecked的唯一解决方案.
聊天示例,您必须在添加和呈现新消息后向下滚动消息列表:
import {Component, AfterViewChecked, ElementRef} from 'angular2/core';
@Component({
selector: 'chat',
template: `
<div style="max-height:200px; overflow-y:auto;" class="chat-list">
<ul>
<li *ngFor="#message of messages;">
{{ message }}
</li>
</ul>
</div>
<textarea #txt></textarea>
<button (click)="messages.push(txt.value); txt.value = '';">Send</button>
`
})
export class ChatComponent implements AfterViewChecked {
public messages: any[] = [];
private _prevChatHeight: number = 0;
constructor (public element: ElementRef) {
this.messages = ['message 3', 'message 2', 'message 1'];
this.elChatList = this.element.nativeElement.querySelector('.chat-list');
}
public ngAfterViewChecked(): void {
/* need _canScrollDown because it triggers even if you enter text in the textarea */
if ( this._canScrollDown() ) {
this.scrollDown();
}
}
private _canScrollDown(): boolean {
/* compares prev and current scrollHeight */
var can = (this._prevChatHeight !== this.elChatList.scrollHeight);
this._prevChatHeight = this.elChatList.scrollHeight;
return can;
}
public scrollDown(): void {
this.elChatList.scrollTop = this.elChatList.scrollHeight;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64828 次 |
| 最近记录: |