[230104 - TIL] angular material dialog로 모달창 띄우기

Dongwoo Kim·2023년 1월 4일
0

TIL / WIL

목록 보기
69/112

1. 프로젝트 셋업

아래에서 작성한 프로젝트 이어서 작업


2. 프로젝트 구조

ng add @angular/material

  • cf) 임포트 에러 발생시
    npm install --save @angular/material
    npm install --save @angular/cdk
AppModule
    ├── (AppService)
	│	
    ├── HomeModule
	│
	└── UserModule
        │
    	└── UserInfoComponent
				│
		   (MatDialog)── UserInfoDetailComponent
  • 더이상 UserInfoDetailComponentUserInfoComponent에 종속되지 않지만 UserInfoComponent내부의 MatDialog에 의해 불러와진다.

3. MatDialog 적용

3-1) AppModule

# app.module.ts

import { MatDialogModule } from '@angular/material/dialog';
@NgModule({
  declarations: [AppComponent],
  imports: [
    ...
    MatDialogModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})

3-2) UserInfoComponent

  • 종속관계가 아닌 UserInfoDetailComponent에서도 동일한 AppService를 바라보기 위해 data에 추가시킨다.
# user/user-info/user-info.component.ts

import { MatDialog } from '@angular/material/dialog';
import { UserInfoDetailComponent } from './user-info-detail/user-info-detail.component';

export class UserInfoComponent implements OnInit {
  constructor(
    @SkipSelf() public appService: AppService,
    public dialog: MatDialog
  ) {}

  ngOnInit(): void {}

  openDialog(): void {
    this.dialog.open(UserInfoDetailComponent, {
      data: this.appService,
    });
  }
}
# user/user-info/user-info.component.html

<h1>User Info Component</h1>
<p>{{ this.appService.user.username }}</p>
<button (click)="openDialog()">모달창 띄우기</button>

3-3) UserInfoDetailComponent

  • addPanelClass를 통해 스타일 클래스를 추가시킨다.
# user/user-info/user-info-detail/user-info-detail.component.ts

import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

export class UserInfoDetailComponent implements OnInit {
  constructor(
    public dialogRef: MatDialogRef<UserInfoDetailComponent>,
    @Inject(MAT_DIALOG_DATA) public data: AppService
  ) {
    dialogRef.addPanelClass('user-info-detail-box');
  }

  ngOnInit(): void {}
}
# user/user-info/user-info-detail/user-info-detail.component.html

<h1>User Info Detail Component!</h1>
<p>{{ this.data.user.created_at }}</p>

3-4) global styles 정의

  • MatDialog에 의해 띄어진 컴포넌트(mat-dialog-container)는 AppModule 밖에 존재한다.
  • 따라서 global styles에 해당 스타일 클래스를 작성하면 addPanelClass로 추가시킨 클래스를 적용시킬 수 있다.
# ../styles.css

.user-info-detail-box {
  background-color: aquamarine;
  color: red;
}

.mat-mdc-dialog-container {
  --mdc-dialog-container-color: rgba(0, 0, 0, 0);
}

4. 적용 화면



구현 코드

https://github.com/kimphysicsman/TIL-230104

참고

profile
kimphysicsman

0개의 댓글