如何在Angular2中使用dom渲染后调用函数?

时间:2015-07-01 20:30:50

标签: angular

我一般都是Angular2和Angular的新手,并且在组件的数据发生更改后更新dom后尝试获取一些jQuery。 jQuery需要计算元素的高度,所以我不能完全使用数据。不幸的是,看起来onAllChangesDone仅在数据更改后触发,而不是dom。

1 个答案:

答案 0 :(得分:58)

我在生命周期挂钩 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;
    }
}