【问题标题】:How can I access ngOffline directive in a component instead of html如何在组件中访问 ngOffline 指令而不是 html
【发布时间】:2021-07-26 15:40:05
【问题描述】:

我正在使用这个 npm 库 https://www.npmjs.com/package/ng-offline 在离线时提醒最终用户。

<div class="alert alert-danger" ngOffline>You're offline. Check your connection!</div>

stackblitz 在这里:https://stackblitz.com/edit/angular-ngoffline-npm?file=src%2Fapp%2Fapp.component.html

效果很好 - 但是 我想用这个 ngOffline 指令打开一个模式,所以我试图从我的 angular 11 组件中访问该指令,但不知道如何要解决这个问题,我们将不胜感激。

我可以用这个指令从 html 中打开一个 ngx-bootstrap 模式吗?

【问题讨论】:

    标签: npm offline angular-directive angular11


    【解决方案1】:

    因为ng-offline 模块没有像您预期的那样导出内容(即,您不能注入一个独立的NgOfflineDirective 供您使用,而无需在您的html 文件中使用它),您可以添加这样的块(您使用#trigger 来识别您的ngOnline 元素):

    import { AfterContentChecked, Component, ElementRef, OnDestroy, ViewChild } from '@angular/core';
    import { BehaviorSubject, Subscription } from 'rxjs';
    import { distinctUntilChanged, filter } from 'rxjs/operators';
    
    @Component({ ... })
    export class YourClass implements AfterContentChecked, OnDestroy {
      offline$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>();
      subscription: Subscription;
    
      @ViewChild('trigger') trigger: ElementRef;
    
      constructor() {
        this.subscription = this.offline$.pipe(
          distinctUntilChanged(),
          filter((offline: boolean) => offline),
        ).subscribe(() => this.showModal());
      }
    
      ngOnDestroy() {
        this.subscription.unsubscribe();
      }
    
      ngAfterContentChecked() {
        if (
          this.trigger &&
          this.trigger.nativeElement
        ) {
          this.offline$.next(this.trigger.nativeElement.style.display === "none");
        }
      }
    
      showModal() {
        console.log('Show your modal here.');
      }
    }
    

    【讨论】:

    • 感谢您的回答,因为它是一个角度应用程序-我尝试了您的答案,但使用了 hostlistener 但不幸的是无法使其正常工作-@HostListener("window:ngOffline", ["$事件"]) openOfflineModal() { this.offlineModal.show(); }
    • 好的,但我确实将该行添加到您的打字稿中,它按预期工作。 ://
    • 它确实会打开一个警报,但不使用我从 npm 使用的库,您的解决方案也会选择本地/浏览器网络,而 npm 上的 ngOffline 包会检测您是否没有 wifi/互联网 - 我需要在组件中使用上面提到的 npm 包而不是 html 打开模式 - 您还有其他建议吗? - 我很高兴听到他们的声音,感谢到目前为止的帮助;)
    • 我实际上从ngOffline 的源代码中删除了那条线。看起来有一个额外的 URL 轮询来检查响应标头。
    • 我已经用你的代码更新了 stackblitz 并试图隐藏/显示基于 wifi 连接的模式 - 最初是使用你的代码 - 连接到互联网时模式正在显示,但我想显示用户断开连接时的模态-如果您可以分叉我的stackblitz并共享链接,那就太好了-我缺少一些小东西但看不到它-非常感谢您到目前为止给我的帮助
    猜你喜欢
    • 2015-10-23
    • 2018-02-11
    • 2017-05-31
    • 2016-12-26
    • 2020-05-30
    • 2017-10-27
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    相关资源
    最近更新 更多