1. 说明
angular-material2自身文档不详,控件不齐,使用上造成了很大的障碍。这里提供一个方案用于封装我们最常用的alert和confirm组件。
2. 官方使用方法之alert
①编写alert内容组件
@Component({template : `<p>你好</p>`})export class AlertComponent { constructor(){ }}
②在所属模块上声明
//必须声明两处declarations: [ AlertComponent],entryComponents : [ AlertComponent]
③使用MdDialg.open方法打开
//注入MdDialog对象constructor(private mdDialog : MdDialog) { }//打开this.mdDialog.open(AlertComponent)
3. 官方使用方法之confirm
①编写confirm内容组件
@Component({template : `<div md-dialog-title>'确认操作'</div> <div md-dialog-content>确认执行操作?</div> <div md-dialog-actions> <button md-button (click)="mdDialogRef.close('ok')">确认</button> <button md-button (click)="mdDialogRef.close('cancel')">取消</button> </div>`})export class ConfirmComponent { constructor(private mdDialogRef : MdDialogRef<DialogComponent>){ }}
②在所属模块上声明
//必须声明两处declarations: [ ConfirmComponent],entryComponents : [ ConfirmComponent]
③使用MdDialog.open打开并订阅相关事件
//注入MdDialog对象constructor(private mdDialog : MdDialog) { }//打开this.mdDialog.open(ConfirmComponent).subscribe(res => { res === 'ok' && dosomething});
4. 分析
如2、3所示,使用material2的对话框组件相当繁琐,甚至仅仅打开一个不同的alert都要声明一个独立的组件,可用性很差。但也不是毫无办法。
MdDialog.open原型:
代码如下:
open<T>(componentOrTemplateRef: ComponentType<T> | TemplateRef<T>, config?: MdDialogConfig): MdDialogRef<T>;
其中MdDialogConfig:
export declare class MdDialogConfig { viewContainerRef?: ViewContainerRef; /** The ARIA role of the dialog element. */ role?: DialogRole; /** Whether the user can use escape or clicking outside to close a modal. */ disableClose?: boolean; /** Width of the dialog. */ width?: string; /** Height of the dialog. */ height?: string; /** Position overrides. */ position?: DialogPosition; /** Data being injected into the child component. */ data?: any;}
具体每一个配置项有哪些用途可以参考官方文档,这里data字段,说明了将会被携带注入子组件,也即被open打开的component组件。怎么获取呢?
config : any;constructor(private mdDialogRef : MdDialogRef<AlertComponent>){ this.config = mdDialogRef.config.data || {};}
新闻热点
疑难解答
图片精选