簡體   English   中英

在從陣列構建mat-tab組時關閉mat-tab后,組件不會被銷毀

[英]Components are not being destroyed after closing a mat-tab when building a mat-tab-group from an array

我有一個數據集,其中有一個面板數組,其中包含有關應該在mat-tab-group中加載的組件的信息。 可以關閉mat-tab組中的選項卡。 為此,我更改了用於構建選項卡組的數據結構。 因此,當我們有一個包含4個面板的數組(在選項卡組中呈現4個選項卡)並且我們刪除一個面板時,該數組將只有3個值,並且只呈現三個選項卡。

問題是刪除的選項卡中的組件實際上將保持活動狀態。 我通過在組件的構造函數中添加一個區間來測試它。 當組件消失時,我預計它真的會消失,但是間隔中的console.log將繼續記錄。

這是最小復制的stackblitz: https ://stackblitz.com/edit/angular-wfkpqq

我做了一些谷歌搜索並檢查了文檔,但我找不到關於關閉mat-tabs的任何信息。 有一個家伙告訴別人這應該由用戶實現,但他們並沒有真正為你提供正確的工具。

如何確保我的孤立組件被破壞?

 import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-dock', templateUrl: './dock.component.html', styleUrls: ['./dock.component.css'] }) export class DockComponent { public dock: any; constructor() { this.dock = { panels: [ { name: 'panel1' }, { name: 'panel2' }, { name: 'panel3' }, { name: 'panel4' } ] } } public onClose(panel): void { var index = this.dock.panels.indexOf(panel); if (index > -1) { this.dock.panels.splice(index, 1); } } } 
 <mat-tab-group #tabs> <ng-container *ngFor="let panel of dock.panels"> <mat-tab> <ng-template mat-tab-label> <div> <span class="tab-title">{{panel.name}}</span> <span style="flex: 1 1 auto;"></span> <div class="tab-options"> <button mat-icon-button (click)="onClose(panel)"> <mat-icon>close</mat-icon> </button> </div> </div> </ng-template> <!-- ng-template with matTabContent makes the tabs lazy load --> <ng-template matTabContent> <app-annoying [name]="panel.name"></app-annoying> </ng-template> </mat-tab> </ng-container> </mat-tab-group> 

[編輯]問題是另一回事。 我分離了一個動態插入的組件,因此我可以移動組件。 關閉組件時我也這樣做,因此面板被分離,因此永遠不會調用OnDestroy。 我會接受唯一的答案,因為它引導我犯錯誤。

我想我知道你的問題是什么。 您的組件正在被銷毀,問題是您沒有關閉間隔。 我使用你的stackblitz玩了arround,如果你添加一個ngOnDestroy(並實現OnDestroy)並關閉間隔,你會發現一切都按預期工作

改變你的annoying.component.ts

    import { Component, OnInit, Input, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-annoying',
  templateUrl: './annoying.component.html',
  styleUrls: ['./annoying.component.css']
})

export class AnnoyingComponent implements OnDestroy {
  @Input() public name: string;
  _interval:any;
  constructor() {
    this._interval = setInterval(() => {
      console.log(this.name + ' still lives');
    }, 1000);
   }

   ngOnDestroy(){
     clearInterval(this._interval);
     console.log(this.name + "is being destroyed");
   }
}

並且您將看到日志"is being destroyed"顯示,而其他日志在您關閉選項卡時停止。

問題在於缺乏

clearInterval(this._interval);

看看這個答案:

https://stackoverflow.com/a/42395773/7041393

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM