在Material Angular中显示一个简单的警告对话框

16

我正在使用Material Angular(来自Angular Material)。该网站中的示例看起来有些过于复杂,互联网上的其他教程似乎要么过时,要么使用AngularJS。我该如何使用标题、消息和确认/取消按钮显示简单的警报(就像Android的AlertDialog)?


这是一个非常好的例子:https://stackblitz.com/angular/dnbaljqbqpea?file=app%2Fdialog-overview-example.ts - Daniel C.
3个回答

24

编辑:

您还可以在组件的HTML文件中使用模板引用(通常称为"组件视图"),然后在组件的TypeScript文件中引用它,再将该引用传递给MatDialog#open

或者,您可以在组件的视图中访问模板的引用,并将其传递给您定义的接受此引用的方法。

如果您对我刚刚输入的内容感到困惑,请查看下面的代码(第一个对话框演示了第一句话,第二个对话框展示了我在第二句话中解释的内容)

(再次假设以下结构)

app/
  app.component.html
  app.component.ts

app.component.html:

<button mat-button (click)="openDialogWithRef(firstDialog)">Open dialog with reference</button>
<button mat-button (click)="openOtherDialog()">Open dialog in code</button>

<ng-template #firstDialog>
  <h2 matDialogTitle>Hello, world!</h2>
  <p matDialogContent><em>Content for this dialog goes here...</em></p>
  <mat-dialog-actions align="end">
    <button mat-button matDialogClose>Dismiss</button>
  </mat-dialog-actions>
</ng-template>

<ng-template #secondDialog>
  <h2 matDialogTitle>Hello, second dialog!</h2>
  <p matDialogContent>Interesting note: This template reference was referenced in code with the <code>@ViewChild</code>, which lets you query components/template references in the component view.</p>
  <mat-dialog-actions align="end">
    <button mat-button matDialogClose>Dismiss</button>
  </mat-dialog-actions>

app.component.ts(缩写):

import { ViewChild, TemplateRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';

// ...
export class AppComponent {
  @ViewChild('secondDialog') secondDialog: TemplateRef<any>;

  constructor(private dialog: MatDialog) { }

  openDialogWithRef(ref: TemplateRef<any>) {
    this.dialog.open(ref);
  }

  openOtherDialog() {
    this.dialog.open(this.secondDialog);
  }
}

使用此方法可以避免为对话框创建新组件以及在模块的entryComponents中声明它们而产生的一些麻烦。

然而,如果在单个组件视图中有多个对话框模板,则这可能很快变得麻烦。


原始回答

以下是您请求的一个简单示例:

(假设以下结构)

app/
  my-alert-dialog/
    my-alert-dialog.component.html
    my-alert-dialog.component.ts
  app.component.ts
  app.module.ts

my-alert-dialog.component.html

<h2 matDialogTitle>Unregister?</h2>
<mat-dialog-content>
  <p>When you unregister, all your data will be removed. Continue?</p>
</mat-dialog-content>
<mat-dialog-actions align="end">
  <!--
    Note that you can pass in anything to the `matDialogClose` attribute. This also includes objects, arrays, etc.
    Just make sure that you make it a property binding with those [] brackets
    Example: <button mat-button [matDialogClose]="{'lol': true}">Cancel</button>
  -->
  <button mat-button matDialogClose="cancel" color="primary">Cancel</button>
  <button mat-button matDialogClose="confirm" color="warn">Unregister</button>
</mat-dialog-actions>

以上代码的解释如下:

  • [matDialogTitle] / [mat-dialog-title]:指令(通常用于 h2 元素),用于指示对话框的标题。
  • [matDialogContent] / [mat-dialog-content] / mat-dialog-content:指令,表示对话框的内容。
  • [matDialogActions] / [mat-dialog-actions] / mat-dialog-actions:指令,表示对话框的操作。
  • [matDialogClose] / [mat-dialog-close]:指令(通常用于 button 元素),表示当点击此元素时应关闭对话框。可选地,此指令可以包括一个参数(任意类型),然后将该参数传递给打开此对话框的组件。

my-alert-dialog.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-alert-dialog', // Replace with your own selector
  templateUrl: './my-alert-dialog.component.html'
})
export class MyAlertDialogComponent { }

app.component.ts(已编辑)

import { MatDialog } from '@angular/material';
import { MyAlertDialogComponent } from './my-alert-dialog/my-alert-dialog.component';
// ...
export class AppComponent {
  constructor(private dialog: MatDialog) { }
  unregister() {
    let dialogRef = this.dialog.open(MyAlertDialogComponent);
    dialogRef.afterClosed().subscribe(result => {
      // NOTE: The result can also be nothing if the user presses the `esc` key or clicks outside the dialog
      if (result == 'confirm') {
        console.log('Unregistered');
      }
    })
  }
}

app.module.ts (redacted)

import { MatDialogModule } from '@angular/material';
import { MyAlertDialogComponent } from './my-alert-dialog/my-alert-dialog.component';

@NgModule({
  declarations: [
    // ...
    MyAlertDialogComponent
  ],
  imports: [
    // ...
    MatDialogModule
  ],
  entryComponents: [
    // See https://material.angular.io/components/dialog/overview#configuring-dialog-content-via-code-entrycomponents-code- for more info
    MyAlertDialogComponent
  ]
})
export class AppModule { }

Demo


2
有没有一种单行的方法,我不需要创建一个组件并使用默认模板? - user1663023
据我所知,目前还不可能。 - Edric
@QianChen 你可以使用模板引用来引用在同一组件 HTML 文件中存在的模板,然后获取该引用并将其传递给 MatDialog#open - Edric
嗨,@Edric。我正在尝试使用你的代码,但是如何将HTML对象传递给dialogMsg?我只能将字符串传递给正文。 - timthekoder
@user3622260 你可以将HTML作为字符串传递,然后在对话框的代码中进行清理,或者传递一个经过清理的HTML版本来设置。 - Edric
啊,没错,Angular这个框架将最简单的东西转化成了15个文件和300行代码。 - Edwin

6
我曾使用过 Sweet Alert。这是在 Angular 中创建警告的最简单和最快的方法。您可以在这里找到有关 Sweet Alert 的更多信息:https://www.freakyjolly.com/angular-sweetalert2-tutorial/#.X2nNxmgzZPY
$ npm install --save sweetalert2

在您的TS文件中使用import Swal from 'sweetalert2';与警告框一起Swal.fire('This is a simple and sweet alert')


我尝试了所有的答案,这个更好,因为它更容易和可定制,任何人阅读都应该使用它。 - Sfp

1
安装npm i @angular/material,为dialog添加component,例如EmployeeDialog
假设您希望在对话框中使用table,并在右上角添加close buttonEmployeeDialog.html文件代码
<div md-dialog-content>
<!-- This button to close dialog -->
<button class="close" mat-button (click)="onNoClick()">
 <mat-icon>close</mat-icon>
 
</button>   
<div>   
 <table>
   <th>Id</th><th>Name</th>Addess<th></th><
   <tr *ngFor="let emp of emplyee; let i = index" border="1">
     <td>{{emp.DeviceID}}</td>
     <td>{{emp.FriendlyName}}</td>
   </tr>
 </table>   
</div>   
</div>

您的 EmployeeDialog.ts 文件应为:
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
export class EmployeeDialog implements OnInit {

  constructor(public dialogRef: MatDialogRef<EmployeeDialog>, @Inject(MAT_DIALOG_DATA) public data: any){ }
  
  //write code to handle close
  }
}

现在,如果你想从SourceComponent打开EmployeeDialog,每当调用Employeelist()函数时,diaglog将会打开。 SourceComponent.ts文件。
public Employeelist()
{
    const dialogRef = this.dialog.open(EmployeeDialog, {
    width: '80%',
    height:'80%',
    panelClass: 'my-dialog',
    disableClose: true ,
    data: employeeList
  });
}

app.module.ts 文件中的代码

import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

import { MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeDialog,
    SourceComponent,
  ],
  imports: [
    MatDialogModule,
    MatButtonModule,
    BrowserModule,
  ],
  entryComponents: [EmployeeDialog],
  bootstrap: [ AppComponent ],
  providers: []
})
export class AppModule { }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接