本文轉自:https://www.cnblogs.com/NeverCtrl-C/p/8125346.html css
MdDialog是一個服務,能夠利用它來打開一個具備material風格和動畫效果的對話框html
技巧01:雖然已經在模塊級別導入了MdDialogModule可是在須要依賴注入MdDialog服務的組件仍然須要單獨導入MdDialog服務編程
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, MdIconRegistry, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule } from '@angular/material'; import { HttpModule } from '@angular/http'; @NgModule({ imports: [ CommonModule, HttpModule, MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule ], declarations: [], exports: [ CommonModule, MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, HttpModule, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule ], providers: [ // MdDialog ] }) export class SharedModule { }
import { Component, OnInit } from '@angular/core'; import { MdDialog } from '@angular/material'; import { Test02Component } from '../test02/test02.component'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'] }) export class TestComponent implements OnInit { color = "red"; constructor( private dialog: MdDialog ) { } ngOnInit() { } openNewProjectDialog() { this.dialog.open(Test02Component, { height: `400px`, width: '400px', data: `hello world` }); } }
利用MdDialog服務提供的open方法能夠打開對話框markdown
格式:this.MdDialog服務實例.open(對話框組件,參數和數據);app
例子:ide
技巧01:須要在使用MdDialog服務的組件引入並引來注入MdDialog服務動畫
import { Component, OnInit } from '@angular/core'; import { MdDialog } from '@angular/material'; import { Test02Component } from '../test02/test02.component'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'] }) export class TestComponent implements OnInit { color = "red"; constructor( private dialog: MdDialog ) { } ngOnInit() { } openNewProjectDialog() { this.dialog.open(Test02Component, { height: `400px`, width: '400px', data: `hello world` }); } }
技巧02:須要將對話框組件this
技巧03:做爲MdDialog組件的書寫格式和md-card組件很相似,只不過是利用指令實現的spa
<form> <h2 md-dialog-title>新建項目</h2> <div md-dialog-content> <md-input-container class="fill-width"> <input mdInput type="text" placeholder="項目名稱" /> </md-input-container> <md-input-container class="fill-width"> <input mdInput type="text" placeholder="項目描述" /> </md-input-container> </div> <div md-dialog-actions> <button md-raised-button type="button" color="primary"> <md-icon>save</md-icon> <span>保存</span> </button> <button md-raised-button type="button" color="accent" (click)="onCloseNewProjectDialog()"> <md-icon>cancel</md-icon> <span>取消</span> </button> </div> </form>
因爲MdDialog是在運行期間進行實例化的,因此Angular須要一些額外的信息纔可以在運行期間建立對話框組件實例。所以,必須將對話框組件在模塊級別進行個別的聲明 -> 將要做爲對話框的組件再在entryComponents中進行一次聲明3d
import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { LoginComponent } from './login/login.component'; import { LoginRoutingModule } from './login-routing.module'; import { RegisterComponent } from './register/register.component'; import { TestComponent } from './test/test.component'; import { Test02Component } from './test02/test02.component'; @NgModule({ imports: [ SharedModule, LoginRoutingModule ], declarations: [ LoginComponent, RegisterComponent, TestComponent, Test02Component ], entryComponents: [ Test02Component ] }) export class LoginModule { }
經過MdDialog建立的對話框組件能夠依賴注入MdDialogRef服務,該服務的close方法能夠用來關閉對話框,並向觸發對話框的組件傳遞一些信息
技巧01:雖然在模塊級別已經導入了MdDialogModule,可是在對話框組件任然要單獨引入MdDialogRef而且經過構造器進行依賴注入
import { Component, OnInit } from '@angular/core'; import { MdDialogRef } from '@angular/material'; @Component({ selector: 'app-test02', templateUrl: './test02.component.html', styleUrls: ['./test02.component.scss'] }) export class Test02Component implements OnInit { constructor( private dialogRef: MdDialogRef<Test02Component> ) { } ngOnInit() { } onSaveClick() { this.dialogRef.close('經過對話框的保存按鈕關閉了對話框'); } }
從MdDialogRef的源碼能夠看出close方法的參數是一個可選參數(可傳可不傳)
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { OverlayRef } from '../core'; import { DialogPosition } from './dialog-config'; import { Observable } from 'rxjs/Observable'; import { MdDialogContainer } from './dialog-container'; import 'rxjs/add/operator/filter'; /** * Reference to a dialog opened via the MdDialog service. */ export declare class MdDialogRef<T> { private _overlayRef; private _containerInstance; /** The instance of component opened into the dialog. */ componentInstance: T; /** Whether the user is allowed to close the dialog. */ disableClose: boolean; /** Subject for notifying the user that the dialog has finished closing. */ private _afterClosed; /** Result to be passed to afterClosed. */ private _result; constructor(_overlayRef: OverlayRef, _containerInstance: MdDialogContainer); /** * Close the dialog. * @param dialogResult Optional result to return to the dialog opener. */ close(dialogResult?: any): void; /** * Gets an observable that is notified when the dialog is finished closing. */ afterClosed(): Observable<any>; /** * Updates the dialog's position. * @param position New dialog position. */ updatePosition(position?: DialogPosition): this; /** * Updates the dialog's width and height. * @param width New width of the dialog. * @param height New height of the dialog. */ updateSize(width?: string, height?: string): this; /** Fetches the position strategy object from the overlay ref. */ private _getPositionStrategy(); }
技巧01:MdDialog的open方法返回的實際上是一個MdDialogRef對象,咱們能夠利用這個MdDialogRef來獲取對話框傳遞過來的數據
技巧02:在利用MdDialogRef對象接收對話框組件傳遞數據的組件不須要在導入和依賴注入MdDialogRef,
import { Component, OnInit } from '@angular/core'; import { MdDialog } from '@angular/material'; import { Test02Component } from '../test02/test02.component'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'] }) export class TestComponent implements OnInit { color = "red"; constructor( private dialog: MdDialog ) { } ngOnInit() { } openNewProjectDialog() { const dialogRef = this.dialog.open(Test02Component, { height: `400px`, width: '400px', data: `hello world` }); dialogRef.afterClosed().subscribe(result => console.log(result)); } }
MD_DIALOG_DATA指令
3.1 簡要描述
MdDialog服務的open方法在打開服務的同時能夠向對話框發送一些數據,可是對話框必須依賴一個服務纔可以接收到這些數據;這個服務對應的令牌就是MD_DIALOG_DATA
技巧01:在對話框組件引入MAT_DIALOG_DATA
令牌,在對話框組件的構造器中依賴注入MD_DIALOG_DATA
令牌對應的服務
import { Component, OnInit, Inject } from '@angular/core'; import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material'; @Component({ selector: 'app-test02', templateUrl: './test02.component.html', styleUrls: ['./test02.component.scss'] }) export class Test02Component implements OnInit { constructor( private dialogRef: MdDialogRef<Test02Component>, @Inject(MD_DIALOG_DATA) private data: any ) { } ngOnInit() { console.log(`對話框接收到的參數爲:${this.data}`); } onSaveClick() { this.dialogRef.close('經過對話框的保存按鈕關閉了對話框'); } }
對話框是不受應用主題控制的,由於對話框是浮動在上面的
在對話框組件中引入並依賴注入OverlayContainer服務來設置對話框的主題
import { Component, OnInit, Inject } from '@angular/core'; import { MdDialogRef, MD_DIALOG_DATA, OverlayContainer } from '@angular/material'; @Component({ selector: 'app-test02', templateUrl: './test02.component.html', styleUrls: ['./test02.component.scss'] }) export class Test02Component implements OnInit { constructor( private dialogRef: MdDialogRef<Test02Component>, @Inject(MD_DIALOG_DATA) private data: any, private oc: OverlayContainer ) { } ngOnInit() { console.log(`對話框接收到的參數爲:${this.data}`); this.oc.themeClass = 'myapp-dark-theme'; } onSaveClick() { this.dialogRef.close('經過對話框的保存按鈕關閉了對話框'); } }
點擊一個按鈕 -> 彈出一個新建項目的對話框,並能夠向該對話框傳遞數據 -> 點擊對話框的關閉按鈕能夠關閉對話框 -> 點擊對話框的保存按鈕也能夠關閉對話框並能向觸發對話框的組件傳遞數據 -> 對話框的主題能夠根據傳遞給對話框的數據進行靈活設置
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, MdIconRegistry, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule } from '@angular/material'; import { HttpModule } from '@angular/http'; @NgModule({ imports: [ CommonModule, HttpModule, MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule ], declarations: [], exports: [ CommonModule, MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, HttpModule, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule ], providers: [ // MdDialog ] }) export class SharedModule { }
import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { ProjectListComponent } from './project-list/project-list.component'; import { ProjectItemComponent } from './project-item/project-item.component'; import { NewProjectComponent } from './new-project/new-project.component'; import { InviteComponent } from './invite/invite.component'; import { ProjectRoutingModule } from './project-routing.module'; @NgModule({ imports: [ SharedModule, ProjectRoutingModule ], declarations: [ ProjectListComponent, ProjectItemComponent, NewProjectComponent, InviteComponent ], entryComponents: [ NewProjectComponent, InviteComponent ] }) export class ProjectModule { }
import { Component, OnInit, Inject } from '@angular/core'; import { MdDialog } from '@angular/material'; import { NewProjectComponent } from '../new-project/new-project.component'; @Component({ selector: 'app-project-list', templateUrl: './project-list.component.html', styleUrls: ['./project-list.component.scss'] // providers: [MdDialog] }) export class ProjectListComponent implements OnInit { projects: any; constructor( private dialog: MdDialog // 依賴注入MdDialog用於打開對話框 ) { } ngOnInit() { this.projects = [ { "name": "MES管理系統", "des": "MES管理系統描述", "coverImg": "assets/img/covers/3.jpg" }, { "name": "青春不朽客戶管理系統", "des": "青春不朽客戶管理系統描述", "coverImg": "assets/img/covers/4.jpg" } ]; } openNewProjectDialog() { // alert("新增項目"); // 打開對話框 const dialogRef = this.dialog.open(NewProjectComponent, { width: "300px", height: "300px", position: {left: "10px", top: "10px"}, data: {dark: true} }); // 對話框關閉時接收對話框傳過來的數據 dialogRef.afterClosed().subscribe(result => console.log(result)); } }
import { Component, OnInit, Inject } from '@angular/core'; import { MD_DIALOG_DATA, MdDialogRef, OverlayContainer } from '@angular/material'; @Component({ selector: 'app-new-project', templateUrl: './new-project.component.html', styleUrls: ['./new-project.component.scss'] }) export class NewProjectComponent implements OnInit { constructor( @Inject(MD_DIALOG_DATA) private data, // 獲取觸發對話框組件傳過來的數據(須要經過令牌來實現注入) private dialogRef: MdDialogRef<NewProjectComponent>, // 關閉對話框並返回數據時須要用到的數據 private oc: OverlayContainer ) { } ngOnInit() { // alert(this.data); console.log(JSON.stringify(this.data)); // 打印獲取到的數據 this.oc.themeClass = this.data.dark ? 'myapp-dark-theme' : null; } onSaveClick() { // 關閉對話框,關閉的同時會向打開對話框的組件傳遞數據 this.dialogRef.close(`I received your message.`); } }
MdAutocompleteModule是一個文本輸入框,它必須配合input標籤使用
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, MdIconRegistry, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule, MdAutocompleteModule } from '@angular/material'; import { HttpModule } from '@angular/http'; @NgModule({ imports: [ CommonModule, HttpModule, MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule, MdAutocompleteModule ], declarations: [], exports: [ CommonModule, MdSidenavModule, MdToolbarModule, MdIconModule, MdButtonModule, HttpModule, MdCardModule, MdInputModule, MdListModule, MdSlideToggleModule, MdGridListModule, MdDialogModule, MdAutocompleteModule ], providers: [ // MdDialog ] }) export class SharedModule { }
<form> <h2 md-dialog-title>成員邀請</h2> <div md-dialog-content> <md-input-container class="full-width"> <input mdInput type="text" placeholder="請選擇成員" [mdAutocomplete]="autoMembers" /> </md-input-container> </div> <div md-dialog-actions> <button type="button" md-raised-button color="primary" >確認</button> <button type="button" md-raised-button color="accent" md-dialog-close >取消</button> </div> </form> <md-autocomplete #autoMembers="mdAutocomplete" [displayWith]="displayValue"> <md-option *ngFor="let item of items" [value]="item"> {{ item.name }} </md-option> </md-autocomplete>
技巧01:若是不給md-autocomplete組件設定displayWith,那麼在input組件顯示的就會是md-input組件value屬性的值
技巧02:給md-input組件指定一個對象時,input的只會是一個對象;利用md-autocomplete組件的displayWith屬性能夠解決這個問題;displayWith的屬性值是一個方法名,該方法的參數就是md-input組件value屬性的值,該方法返回的值就是input組件最後顯示的值
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-invite', templateUrl: './invite.component.html', styleUrls: ['./invite.component.scss'] }) export class InviteComponent implements OnInit { items : any; constructor() { } ngOnInit() { this.items = [ { id: 1, name: '喬峯' }, { id: 2, name: '慕容復' }, { id: 3, name: '段譽' }, { id: 4, name: '虛竹' } ]; } // 設置顯示內容 displayValue(member: {id: number; name: string}) { return member ? member.name : null; } }