代码之家  ›  专栏  ›  技术社区  ›  Yashwardhan Pauranik kizu

新邮件滚动到底部

  •  -1
  • Yashwardhan Pauranik kizu  · 技术社区  · 7 年前

    我有一个角度应用程序,每当有新消息到达时,我都会遇到聊天容器中自动滚动到底部的问题。

    我的模板

    <div #msgContainer class="chat-box-body" appInfiniteScroll (scrollTop)="loadOlderMessages()">
     <ng-container *ngFor="let msg of conversation.messages.edges">
      <ng-container *ngIf="msg.node?.from?.id !== currentUser.id; else myMsg">
        <div class="sender-msg-block">
          <div class="wrapper-left">
            <img class="sender-dp"
                 [src]="conversation.conversation_participants[0].conversable?.profile_picture?.url ||  'assets/images/no-user.svg'">
            <p class="sender-msg">{{msg.node.body}}</p>
            <span class="sender-time">{{msg.node.created_at}}</span>
          </div>
        </div>
      </ng-container>
      <ng-template #myMsg>
        <div #newMesssage class="receiver-msg-block">
          <div class="wrapper-right">
            <span class="receiver-time">{{msg.node.created_at}}</span>
            <p class="receiver-msg">
              {{msg.node.body}}
            </p>
          </div>
        </div>
      </ng-template>
    </ng-container>
    

    当我收到新消息时。此订阅在此函数中激发:

    listenIncomingMessages() {
    this.chatService.messageReceived$
      .pipe(
        takeWhile(() => this.isAlive)
      )
      .subscribe((data: any) => {
        if (data) {
          const newEdge = {
            node: data
          };
          if (data.conversation_id === this.conversationId) {
            this.conversation.messages.edges = <any>[...this.conversation.messages.edges, newEdge];
            // TODO: Scroll to bottom not working
            this.msgContainer.nativeElement.scrollTop =
              this.msgContainer.nativeElement.scrollTop + this.newMesssage.nativeElement.scrollHeight;
          }
        }
      });
    }
    

    请帮忙。谢谢:)

    1 回复  |  直到 7 年前
        1
  •  0
  •   BlizZard    7 年前

    ngAfterViewChecked 为了你的帮助 link

    先申报

    @ViewChild('scrollMe') private myScrollContainer: ElementRef;
    

    在您的.ts文件中。然后进入 ngOnInit()

    ngAfterViewChecked() {
        this.scrollToBottom();
      }
    
    
    
    scrollToBottom(): void {
        try {
          this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
        } catch (err) { }
      }