【问题标题】:Call directive's method from component - Angular 9从组件调用指令的方法 - Angular 9
【发布时间】:2020-06-16 11:51:14
【问题描述】:

我正在尝试在 Angular 9 PWA 中构建一个聊天组件。现在我想知道在聊天窗口中显示新消息时如何实现“自动滚动到底部”功能。

为此,我创建了一个自定义 ScrollToBottom 指令,并将其应用于聊天 DIV 容器。

<div class="msg_history" scrollToBottom>
   <li class="message" *ngFor="let message of messages | async">

在这个指令中,我有一个名为 scrollToBottom 的方法。

public scrollToBottom() {
    const el: HTMLDivElement = this._el.nativeElement;
    setTimeout(() => el.scrollTop = Math.max(0, el.scrollHeight - el.offsetHeight));
  }

现在,我的问题是,在对话主题收到新消息后,是否可以(以及如何?)从 Chat 组件调用指令的方法。

//In component
this.chatService.conversation.subscribe(() => DIRECTIVE.scrollToBottom());

或者更好的方法是省略聊天组件并直接在指令中注入聊天服务,以便在那里处理对话主题更改?

@Directive({
  selector: '[scrollToBottom]'
})
export class ScrollToBottomDirective {
  constructor(private _el: ElementRef, private chat: ChatService) { }

  public ngAfterViewInit() {
    this.chat.conversation.subscribe(() => this.scrollToBottom());
  }

  public scrollToBottom() {
    const el: HTMLDivElement = this._el.nativeElement;
    setTimeout(() => el.scrollTop = Math.max(0, el.scrollHeight - el.offsetHeight));
  }
}

谢谢转发;-)

【问题讨论】:

    标签: angular chat angular-directive


    【解决方案1】:

    是的,在聊天组件中,您可以利用 ViewChild 装饰器来获取对当前组件中的组件\指令的引用

    @ViewChild(ScrollToBottomDirective) child: ScrollToBottomDirective;
    
    //In component
    this.chatService.conversation.subscribe(() => this.child.scrollToBottom());
    

    【讨论】:

    • 酷,很好用,谢谢。也许只是对其他观众的一个提示。这个带有 viewchild 的订阅需要在 ngAfterViewInit() 中
    猜你喜欢
    • 2021-09-30
    • 2018-02-07
    • 1970-01-01
    • 2020-05-30
    • 2017-07-12
    • 2018-06-24
    • 2017-11-16
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多