1. 打開彈窗的點擊事件
project.component.html
<button mat-icon-button class="action-button" (click)="editDialog(project)">
<mat-icon>create</mat-icon>編輯
</button>
<button mat-mini-fab color="warn" class="add-project" (click)="openDialog()"> <mat-icon>add</mat-icon> </button>
project.component.ts
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material';
import { NewProjectComponent } from '../new-project/new-project.component';
@Component({
selector: 'app-project',
templateUrl: './project.component.html',
styleUrls: ['./project.component.scss']
})
export class ProjectComponent implements OnInit {
projects=[
{
"name":'企業協作平台',
"desc":'這是一個企業內部項目',
"coverImg":'assets/img/covers/0.jpg'
},
{
"name":'員工管理平台',
"desc":'這是一個企業內部項目',
"coverImg":'assets/img/covers/1.jpg'
}
];
constructor(public dialog:MatDialog) { }
ngOnInit() {
}
// 新建項目
openDialog(){
const dialogRef = this.dialog.open(NewProjectComponent, {
width: '250px'
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed',result);
});
}
// 編輯項目
editDialog(data){
const dialogRef = this.dialog.open(NewProjectComponent,{
width:'250px',
data:data
});
dialogRef.afterClosed().subscribe(result=>{
console.log('The dialog was closed',result);
})
}
}
2. 彈窗
new-project.component.html
<h1 mat-dialog-title>新建項目</h1>
<div mat-dialog-content>
<mat-form-field>
<input matInput [(ngModel)]="project.name" placeholder="項目名稱">
</mat-form-field>
<mat-form-field>
<input matInput [(ngModel)]="project.desc" placeholder="項目描述">
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-raised-button (click)="onNoClick()">關閉</button>
<button mat-raised-button [mat-dialog-close]="project" cdkFocusInitial color="primary">保存</button>
</div>
new-project.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
@Component({
selector: 'app-new-project',
templateUrl: './new-project.component.html',
styles: []
})
export class NewProjectComponent implements OnInit {
project:Object;
constructor(
public dialogRef:MatDialogRef<NewProjectComponent>,
@Inject(MAT_DIALOG_DATA) public data
) { }
ngOnInit() {
this.project = this.data||{};
}
onNoClick(){
this.dialogRef.close();
}
}
3. 特別注意:new-project組件是一個服務。在project.module.ts中必須寫入entryComponent中,否則會報錯
import { NgModule } from '@angular/core';
import { ProjectComponent } from './project/project.component';
import { SharedModule } from '../shared/shared.module';
import { NewProjectComponent } from './new-project/new-project.component';
@NgModule({
imports: [
SharedModule
],
declarations: [ProjectComponent, NewProjectComponent],
entryComponents:[
NewProjectComponent
]
})
export class ProjectModule { }
