一般的软件应用中都会有一些信息提示框,比如单纯提示一条信息,用户点击确定即可;又比如某些操作之前弹框让用户确认是或否。
利用Angular Material中的Dialog组件,可以制作这些提示框。目前制作了两个:提示框Hint和确认框Prompt。
先说只有一个确定按钮的信息提示框:
1. HTML模板
hint.html
<h2 mat-dialog-title style="font-family: 微软雅黑;">提示</h2><mat-dialog-content class="mat-typography"><p>{{message}}</p></mat-dialog-content><mat-dialog-actions align="end"><button mat-button [mat-dialog-close]="true" cdkFocusInitial>确定</button></mat-dialog-actions>
2. 对话框的TS类
hint.ts
import { Component, Inject } from '@angular/core';import { MAT_DIALOG_DATA} from '@angular/material/dialog';@Component({selector: 'hint',templateUrl: './hint.html',})export class Hint {constructor(@Inject(MAT_DIALOG_DATA) public message: string) { }}
3. 在Component中调用提示框
import { Hint } from '../common/dlg/hint';export class DeviceComponent implements OnInit {constructor(...public dialog: MatDialog,) { }this.dialog.open(Hint, {data:"请选择一条记录!"}); //打开信息提示框}
效果:
带有Yes or No两个按钮的操作确认框(Prompt)和信息提示框基本一样,就多一个按钮, 可以为每个按钮分别设置Yes or No的属性,Yes就设成true,No就设成false.
<button mat-button [mat-dialog-close]="false">不</button><button mat-button [mat-dialog-close]="true" cdkFocusInitial>是的</button>
效果:
4. 使用按钮结果
有时候对于用户按了不同按钮的结果要进行处理,比如按了Yes怎么处理,按了No怎么处理。
const dialogRef = this.dialog.open(Prompt, obj);dialogRef.afterClosed().subscribe(result => { //Dialog的afterClosed事件,挺有用if(result){//Yes...}else{//No...}});