在Angular2中dom渲染后如何调用函数? [英] How to call function after dom renders in Angular2?

查看:83
本文介绍了在Angular2中dom渲染后如何调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一般对Angular2和Angular都是陌生的,并且当组件的数据更改时,在dom更新后,我试图使一些jQuery能够启动. jQuery需要计算元素的高度,所以我不能只使用数据.不幸的是,看起来onAllChangesDone仅在数据更改后才触发,而不是dom.

I am new to Angular2 and Angular in general and am trying to get some jQuery to fire after the dom is updated when the data of a component is changed. The jQuery needs to calculate heights of elements so I can't exactly just use the data. Unfortunately it looks like onAllChangesDone only fires after data changes, not the dom.

推荐答案

我找到的唯一带有生命周期挂钩 ngAfterViewChecked 的解决方案.

The only solution I've found with the lifecycle hook ngAfterViewChecked.

聊天示例,您必须在添加和呈现新消息后向下滚动消息列表:

Example of a chat where you have to scroll down the messages list after adding and rendering a new message:

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;
    }
}

这篇关于在Angular2中dom渲染后如何调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆