環(huán)境:
Angular 4.0.0
Angular2 Material2 2.0.0-beta.3
node v7.4.0
npm 4.0.5
使用 Angular2 Material2 原有的組件并不通用剥懒,比如要不同的模塊使用組件Snackbar场仲,就需要在各個(gè)模塊中分別定義和使用組件,這樣就相當(dāng)繁瑣揍很,不容易復(fù)用雷则,減慢開發(fā)速度辆雾。
官方使用方法請(qǐng)參考Angular2 Material2 使用教程
使用Snackbar封裝alert消息提示框
來,首先來看效果圖~
這三個(gè)分別是成功月劈,警告度迂,失敗的提示信息。
1.創(chuàng)建通用服務(wù)alert.service.ts
在需要使用到的地方注入該服務(wù)艺栈,并調(diào)用方法即可使用英岭。提示信息可以根據(jù)需要傳入。
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']; // 設(shè)置樣式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']; // 設(shè)置樣式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']; // 設(shè)置樣式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
<!-- 成功提示 -->
<button md-raised-button (click)="success()">Success</button>
<!-- 警告提示 -->
<button md-raised-button (click)="warning()">Warning</button>
<!-- 失敗提示 -->
<button md-raised-button (click)="fail()">Fail</button>
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("刪除失敗");
}
}