angular - How to call function after dom renders in Angular2 -
this question has answer here:
i new angular2 , angular in general , trying jquery fire after dom updated when data of component changed. jquery needs calculate heights of elements can't use data. unfortunately looks onallchangesdone fires after data changes, not dom.
the solution i've found lifecycle hook ngafterviewchecked.
example of chat have scroll down messages list after adding , rendering new message:
import {component, afterviewchecked, elementref} '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 triggers if enter text in textarea */ if ( this._canscrolldown() ) { this.scrolldown(); } } private _canscrolldown(): boolean { /* compares prev , 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; } }
Comments
Post a Comment