第5回 Angular Material 徹底解説!- Dialog

プログラミング
スポンサーリンク

本記事でできること

環境

$ npm -v
7.21.1
$ node -v
16.9.1

環境構築はこちら

第1回 Angular Material 徹底解説!- 環境構築
キジ(@kiji)です。みなさんは、Webアプリケーション開発のときにどのフレームワークを使っていますか?React、Vue、最近ではFlutterも候補にあがるでしょうか。 私はというと、ずっとAngularを使ってきました。Angula

説明

タグ 説明
mat-dialog-title タイトル。
mat-dialog-content コンテンツ部。注意書きや利用規約など。
mat-dialog-actions ボタン群。OK、キャンセルなど。
mat-dialog-close ボタンに付けるタグ。このタグを付けることで、モーダルを閉じるボタンにすることができる。また、引数はafterClosedイベントハンドラの引数になる。

モーダルは、buttonなどをクリックした際、MatDialogのopenメソッドを実行することで開きます。openメソッドには、モーダルに利用するコンポーネントと、コンポーネントに渡すパラメータを設定できます。

ソースコード


<div class="content">
<app-dialog></app-dialog>
</div>


・・・
import { DialogComponent } from './sample/dialog/dialog.component';
import { DialogPageComponent } from './sample/dialog/dialog-page/dialog-page.component';
import { MatDialogModule } from '@angular/material/dialog';
・・・
@NgModule({
declarations: [
・・・
DialogComponent, // 追加
DialogPageComponent // 追加
],
imports: [
・・・
MatDialogModule, // 追加
・・・
],
schemas : [ CUSTOM_ELEMENTS_SCHEMA ],
providers: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

view raw

app.module.ts

hosted with ❤ by GitHub


<h2 mat-dialog-title>Dialog Sample</h2>
<mat-dialog-content class="mat-typography">
<h3>{{data}}</h3>
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button (click)="onNoClick()">キャンセル</button>
<button mat-button mat-dialog-close="123" cdkFocusInitial>OK</button>
</mat-dialog-actions>


import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-dialog-page',
templateUrl: './dialog-page.component.html',
styleUrls: ['./dialog-page.component.scss']
})
export class DialogPageComponent implements OnInit {
constructor(
public ref : MatDialogRef<DialogPageComponent>,
@Inject(MAT_DIALOG_DATA) public data : string
) { }
ngOnInit(): void {
}
onNoClick() : void {
this.ref.close("456");
}
}


<button mat-raised-button (click)="openDialog()">開く</button>


import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DialogPageComponent } from './dialog-page/dialog-page.component';
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit {
constructor(private dialog : MatDialog ) { }
ngOnInit(): void {
}
openDialog() : void {
const ref = this.dialog.open(DialogPageComponent, { data : 'test'});
ref.afterOpened().subscribe( () => {
console.log(`modal opened`);
});
ref.afterClosed().subscribe( result => {
console.log(`modal closed result => ${result}`);
});
}
}

GitHubはこちら

GitHub - kiji-tech/blog-angular-material
Contribute to kiji-tech/blog-angular-material development by creating an account on GitHub.

参考

コメント

タイトルとURLをコピーしました