【问题标题】:Angular: update a child boolean component from parent componentAngular:从父组件更新子布尔组件
【发布时间】:2021-08-30 14:17:22
【问题描述】:

我在子组件中有一个按钮,当它被点击时会触发加载器。并且在父组件中可观察,我想在加载 Pdf 时停止加载器

这样做的子组件:

<nsnet-loader *ngIf="pdfLoading"></nsnet-loader>
<button
(click)="triggerLoader()"
[ngClass]="{'is-not-loading': !pdfLoading}"
>
<span>Download</<span>
</button>

export class ButtonDownloadComponent implements OnChanges {
  @Input() check = false;
  pdfLoading = false;

  triggerLoader() {
   this.pdfLoading = true;
  }

 ngOnChanges(changes: SimpleChanges): void {
  if (this.check) {
    this.pdfLoading = false;
  }
 }
}

以及父组件

...
<button-download
(click)="getUrl(devis)"
[check]="stopLoader()"
>
</button-download>
...

stopLoader(): boolean {
  return true;
}

getUrl(devis: Devis) {
 
 setTimeout(() => { this.stopLoader() }, 2000)

 this.xxx.subscribe((res: Blob) => {
  // some logics
  this.stopLoader();
 }
}

我不明白为什么它不起作用...加载器仍在运行

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您的父母正在订阅某些东西.. 但是什么?我在孩子身上看不到主题或可观察到的东西。或.next()。这里有点不对劲。

    在Child中,设置一个Subject被观察

    import { Subject } from 'rxjs';
    
    export class ButtonDownloadComponent implements OnChanges {
      @Input() check = false;
      pdfLoading = false;
      loaded$ = new Subject<Blob>
    
      triggerLoader() {
       this.pdfLoading = true;
      }
    
     ngOnChanges(changes: SimpleChanges): void {
      if (this.check) {
        this.pdfLoading = false;
        loaded$.next(this.res); // you are passing a blob back to parent, so whatever that value is here
      }
     }
    }
    

    在 Parent 中订阅 Subejct 并取消订阅 onDestroy

    import { Subscription } from 'rxjs';
    import { OnDestroy } from '@angular/core';
    
    loadedSub: Subscription;
    
    stopLoader(): boolean {
      return true;
    }
    
    getUrl(devis: Devis) {
     setTimeout(() => { this.stopLoader() }, 2000)
     loadedSub = this.xxx.subscribe((res: Blob) => {
      // some logics
      this.stopLoader();
     }
    }
    
    ngOnDestroy() {
       loadedSub.unsubscribe()
    }
    

    【讨论】:

    • @Younes - 这有助于解决您的问题吗?如果是这样,请接受作为答案。谢谢
    猜你喜欢
    • 2018-09-14
    • 2018-07-15
    • 2021-02-10
    • 2019-08-27
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 2021-03-25
    相关资源
    最近更新 更多