Angular Material 销毁对话框实例

标签 angular angular-material2

是否有适当的方法来销毁由对话框创建的组件实例。 当我关闭对话框时,组件实例未被处理:

import { Component, OnInit, Input, Output, EventEmitter, Inject } from '@angular/core';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';

@Component({
    selector: 'basket',
    templateUrl: './basket.component.html',
    styleUrls: ['./basket.component.css']
})
export class BasketComponent implements OnInit {
    @Input() Product: any;
}

@Component({
    selector: 'basket-dialog',
    template: '<div><basket [Product]="Product"></basket></div>'
})
export class BasketDialogComponent implements OnInit {
    Product: any;
    constructor(public dialogRef: MdDialogRef<BasketComponent>,
        @Inject(MD_DIALOG_DATA) public productData: any) { }


    ngOnInit() {
        this.Product = this.productData;
        this.say();
    }

    say() {
        setTimeout(() => this.say(), 1000);
        console.log('test');
    }
}

创建对话框:

let ordersDialog = this.dialog.open(BasketDialogComponent, {
    data: product
});
ordersDialog.afterClosed().subscribe(x => {
   // something like: orderDialog.componentInstance.dispose();
});

即使对话框关闭,say() 方法仍在执行。

最佳答案

你应该关心自己处理setTimeout:

export class BasketDialogComponent implements OnInit, OnDestroy {

  timeoutId;

  say() {
    this.timeoutId = setTimeout(() => this.say(), 1000);
    console.log('test');
  }

  ngOnDestroy() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
  }
}

Plunker Example

关于Angular Material 销毁对话框实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46254297/

相关文章:

javascript - 为什么 Angular 无法识别用户是否使用 keycloak 登录?

css - 悬停时问题垫形成场轮廓背景颜色

带路由器的 Angular2 Material 设计 mdtabs

asp.net - 如何将 Angular Material 添加到 asp.net Angular 模板

angular - ngClass mat-radio-button 如果选中/Angular

javascript - Angular HttpInterceptor 通过共享 observable 来缓存并行请求

javascript - 在表内加载另一个组件会意外地在Angular中扩展我的表宽度

jboss 7.1.1 上的 Angular 5 独立部署

javascript - RxJs map函数导致upstream observable被多次调用

angular - 在 Angular 中包装 html 标签绑定(bind)的 UI 组件