x秒后自动关闭“角度”对话框

时间:2020-04-30 16:56:31

标签: angular angular-material

我有一个带有欢迎消息的角度对话框。我想在x秒(3-5秒)后自动关闭此对话框。 有人可以指出我的解决方案,文章或文档该怎么做吗?

很多, 皮特

2 个答案:

答案 0 :(得分:1)

如果您使用的是material dialogMatDialogRef<T>服务创建的MatDialog对象具有close功能。

这是非常简化的示例。

import {Component, Inject} from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';

@Component({
  selector: 'content',
  template: '<button mat-raised-button (click)="openDialog()">Open dialog</button>',
  styles: [''],
})
export class Content {

  constructor(public dialog: MatDialog) {}

  openDialog(): void {
    const timeout = 3000;
    const dialogRef = this.dialog.open(Dialog, {
      width: '300px',
      data: {}
    });

    dialogRef.afterOpened().subscribe(_ => {
      setTimeout(() => {
         dialogRef.close();
      }, timeout)
    })
  }
}

@Component({
  selector: 'dialog',
  template: `
<div>
   Dialog
</div>
<div mat-dialog-actions>
  <button mat-button (click)="closeDialog()">Close</button>
</div>`,
})
export class Dialog {

  constructor(
    public dialogRef: MatDialogRef<Dialog>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) {}

  closeDialog(): void {
    this.dialogRef.close();
  }

}

答案 1 :(得分:1)

对于Boostrap模态,您必须首先通过viewchild获取模态的引用。

@ViewChild('closeModal') closeModal: ElementRef


@Component({
  ...
})
export class myComponent extends myModal {

  @ViewChild('closeModal') closeModal: ElementRef

  ...

}

当您需要关闭模式时,只需调用:this.closeModal.nativeElement.click()

例如:

public googleLogin(content): void {
   this.auth.authenticateUser().then((res: any) => {
      setTimeOut(()=>{
         // close the modal in this moment.
         this.closeModal.nativeElement.click() //<-- here

         const user = res.user;
         this.router.navigate(['/gallery']);
      },8000);
   });
}

在您的html中,将#closeModal添加到按钮:

<button #closeModal type="button" class="close" aria-label="Close" (click)="d('Cross click')">
    <span aria-hidden="true">&times;</span>
</button>

了解有关引导模式here的更多信息。

材料设计:您将不得不使用注入到组件中的材料对话框服务。

constructor(
  public dialogRef: MatDialogRef<Dialog>,
  @Inject(MAT_DIALOG_DATA) public data: DialogData
) {}

closeModalDialog(): void {
  this.dialogRef.close();
}

onDialogOpen(): void {
  let dialogRef = this.dialog.open(Dialog);

  setTimeout(() => {
     dialogRef.close();
  }, 80000) ==========> set time here 
}

了解有关材料角模态here的更多信息。