设计一个聊天网页,需要把显示聊天内容的div自动滚屏到底部,但是div缺少scrollTo函数,变通的方法是
div.scrollTop = div.scrollHeight
但在angular中,如何找到这个时机呢? ngFor执行完毕是个时机,但ngFor语句没有提供finished事件。这个事件只能自己制造。
<li *ngFor="let item in Items; let last = last"> ... <span *ngIf="last">{{ngForCallback()}}</span> </li>
public ngForCallback() { ... }
推荐使用AfterViewChecked and @ViewChild 方法,下面详细介绍:
在component中:
import {...,AfterViewChecked,ElementRef,ViewChild,OnInit} from 'angular2/core' @Component({ ... }) export class ChannelComponent implements OnInit,AfterViewChecked { @ViewChild('scrollMe') private myScrollContainer: ElementRef; //ngOnInit() { // this.scrollToBottom(); //} ngAfterViewChecked() { this.scrollToBottom(); } scrollToBottom(): void { try { this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; } catch(err) { } } }
在template中:
<div #scrollMe style="overflow: scroll; height: xyz;"> <div class="..." *ngFor="..." ...> </div> </div>
AfterViewChecked的缺陷是每次组件试图检查后都调用,input控件中,每次keyup都需要检查,调用次数太多。
参考资料:
- http://stackoverflow.com/questions/35819264/angular-2-callback-when-ngfor-has-finished
- http://stackoverflow.com/questions/35232731/angular2-scroll-to-bottom-chat-style
原文地址:https://www.jb51.cc/angularjs/147486.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。