Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当视图在Angular2中完全更新时调用函数_Angular - Fatal编程技术网

当视图在Angular2中完全更新时调用函数

当视图在Angular2中完全更新时调用函数,angular,Angular,我的应用程序将显示消息列表(带滚动条)。当用户添加新消息时,页面需要滚动到消息列表的底部。将新消息添加到消息列表后立即调用scrollToBottom()是否正确?还是会带来时间问题?视图是否已更新(包含新消息),因此scrollHeight是否正确?或者用其他方式来表述我的问题:是否有办法知道/确保视图在模型更改时完全更新 查看(messaging.html): ... 如果要在视图完全加载时调用函数,则可以调用angular2的默认生命周期挂钩,即ngAfterViewinit() 更多信

我的应用程序将显示消息列表(带滚动条)。当用户添加新消息时,页面需要滚动到消息列表的底部。将新消息添加到消息列表后立即调用scrollToBottom()是否正确?还是会带来时间问题?视图是否已更新(包含新消息),因此scrollHeight是否正确?或者用其他方式来表述我的问题:是否有办法知道/确保视图在模型更改时完全更新

查看(messaging.html):


...

如果要在视图完全加载时调用函数,则可以调用angular2的默认生命周期挂钩,即
ngAfterViewinit()

更多信息请参见此处

据官员称

实现此接口以在组件的视图已完全初始化时获得通知

由于您需要在每次视图更改后调用函数,所以可以使用
ngAfterViewchecked

实现此接口以在每次检查组件视图后获得通知


请参阅此处的详细信息

nAfterViewInit()仅在启动/初始化时调用。所以在我添加了一条新消息之后。但是根据你的回答,我发现,在查看检查后,我认为这可能是解决方案?是的,查看的生命周期很少,你可以在这里检查
import {Component, ViewChild, ElementRef} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';

@Component({
  selector: 'messaging',
  templateUrl: './messaging.html',
  styleUrls: ['./messaging.css'],
  directives: [CORE_DIRECTIVES]
})
export class Messaging {
  private messages:Message[] = [];

  @ViewChild('messagingscroll') private messageScroll: ElementRef;

  constructor() {
  }

  sendMessage(message:string, element) {
    let msg:Message = new Message(message);

    // Add msg
    this.messages.push(msg);

    // Scroll to bottom
    this.scrollToBottom();

    // Set back empty
    element.value = '';
  }

  scrollToBottom(): void {
    this.messageScroll.nativeElement.scrollTop = this.messageScroll.nativeElement.scrollHeight;
  }
}