Angular2 Material2 封装组件 —— alert 消息提示框

环境:

Angular 4.0.0
Angular2 Material2 2.0.0-beta.3
node v7.4.0
npm 4.0.5

使用 Angular2 Material2 原有的组件并不通用,比如要不同的模块使用组件Snackbar,就需要在各个模块中分别定义和使用组件,这样就相当繁琐,不容易复用,减慢开发速度。

官方使用方法请参考Angular2 Material2 使用教程

使用Snackbar封装alert消息提示框

源代码

来,首先来看效果图~


成功的消息提示框
警告的消息提示框
失败的消息提示框

这三个分别是成功,警告,失败的提示信息。

1.创建通用服务alert.service.ts

在需要使用到的地方注入该服务,并调用方法即可使用。提示信息可以根据需要传入。

import { Injectable } from '@angular/core';
// 引入官方组件
import { MdSnackBar, MdSnackBarConfig } from '@angular/material';

@Injectable()
export class alertService {

    constructor(public snackBar: MdSnackBar) { }

    // 配置 MdSnackBar 属性
    actionButtonLabel: string = '确定'; 
    action: boolean = true; 
    setAutoHide: boolean = true; 
    autoHide: number = 10000;
    addExtraClass: boolean = false;

    // 成功
    public alertSuccess(msg) {
        let config = new MdSnackBarConfig();
        config.duration = this.autoHide;
        config.extraClasses = ['alertSuccess']; // 设置样式alertSuccess
        this.snackBar.open(msg, this.action && this.actionButtonLabel, config);
    }

    // 警告
    public alertWarning(msg) {
        debugger;
        let config = new MdSnackBarConfig();
        config.duration = this.autoHide;
        config.extraClasses = ['alertWarning']; // 设置样式alertWarning
        this.snackBar.open(msg, this.action && this.actionButtonLabel, config);
    }
    // 失败
    public alertFail(msg) {
        debugger;
        let config = new MdSnackBarConfig();
        config.duration = this.autoHide;
        config.extraClasses = ['alertFail']; // 设置样式alertFail
        this.snackBar.open(msg, this.action && this.actionButtonLabel, config);
    }
}

2.定义样式。文件:alert.component.css

.alertSuccess{
  background: #009688 !important;
}

.alertWarning{
  background: #FDD835 !important;
}

.alertFail{
  background: #E53935 !important;
}

用法( alert.service 中使用样式 ):

config.extraClasses = ['alertSuccess'];
config.extraClasses = ['alertWarning'];
config.extraClasses = ['alertFail'];

3.使用例子

alert.component.html






alert.component.ts
import { Component, ViewEncapsulation } from '@angular/core';
import { MdSnackBar, MdSnackBarConfig } from '@angular/material';
import { alertService } from './alert.service';

@Component({
    moduleId: module.id,
    selector: 'alert',
    templateUrl: './alert.component.html',
    styleUrls: ['./alert.component.css'],
    encapsulation: ViewEncapsulation.None,
    providers: [alertService]
})
export class AlertComponent {
    public constructor(private _alertService: alertService) { }

    public success() {
        this._alertService.alertSuccess("添加成功");
    }
    public warning() {
        this._alertService.alertWarning("警告!");
    }
    public fail() {
        this._alertService.alertFail("删除失败");
    }
}

你可能感兴趣的:(Angular2 Material2 封装组件 —— alert 消息提示框)