Angular

Angular Custom Modal -共用元件實作 - 彈窗 (3)

陳建融 Randy Chen 2022/05/24 14:47:58
791

學習目標

  1. 將製作好的彈窗共用元件在其他的元件引用並使用

專案執行預期結果

在 index 頁面和 test 頁面中各自引用 modal 元件,並可在各自的頁面透過點擊各自頁面中的按鈕來喚出 modal 並關閉它。

使用 modal 元件

引入 modal 並匯出它

在這系列的第一篇文章中,我們有創出 modal.module.ts 這個檔案,我們會在這個檔案中宣告 (declaration) 彈窗元件,並匯出 (export) 它,好讓其他元件可以使用它。

// --- modal.module.ts --- //
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModalComponent } from './modal.component';

@NgModule({
  declarations: [ModalComponent], // 宣告 modal 元件
  imports: [
    CommonModule
  ],
  exports: [ModalComponent]       // 匯出 modal 元件
})
export class ModalModule { }

宣告 modal 元件並使用它

接下來,我們要先在 index 元件使用彈窗元件。
所以,我們要先在 index.module.ts 中引用 ModalModule (負責宣告並匯出彈窗元件的模組)
如此一來,我們就可以在 index 元件裡面使用彈窗元件囉。
程式碼如下

// --- index.module.ts --- //
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { IndexComponent } from './index.component';
import { ModalModule } from '../modal/modal.module';
const routes: Routes = [
  {
    path: '',
    component: IndexComponent
  }
]

@NgModule({
  declarations: [IndexComponent],
  imports: [
    CommonModule,
    ModalModule,                  // 引入 modal 模組
    RouterModule.forChild(routes)
  ]
})
export class IndexModule { }

 

接下來在 index 元件上加入彈窗的內容

// --- index.component.html --- //
<h1>這是首頁</h1>
<button type="button" [routerLink]="['/test']">轉導到 test 頁面</button>

<button type="button" (click)="onModalOpenClick(modal)">開啟 modal</button>
<app-modal #modal>
  <p>這是首頁的 modal </p>
</app-modal>

最後,在 index 元件中加入開啟彈窗的方法

// --- index.component.ts --- //
import { Component, OnInit } from '@angular/core';
import { ModalComponent } from '../modal/modal.component';
@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  onModalOpenClick(modalRef: ModalComponent): void {
    modalRef.modalService.open();
  }
}

在 onModalOpenClick 的參數是傳入 ModalComponent 型別的內容,如此一來我們就能調用 modal 元件中所擁有的 modalService 實例的 open,來為 index 頁面中的 modal 的 class 加入 show 這個 class,最終達到 modal 漸入的效果。

以上的程式碼最終呈現的效果如下


那在 test 元件引入 modal 的方式,一模一樣,先在 test.module.ts 中引入 modal 的模組,接著,加入 modal 的內容在 test.component.html 裡面,最後在定義開啟 modal 的方法。這部分的程式碼我就先不贅述囉~

這一系列製作 Angular 彈窗共用元件的文章就到這邊~~~

結論

  1. 紀錄如何在不同的頁面中,引入彈窗共用元件

 

Reference

  1. How to encapsulate a component to let other component to import it and use it
  2. How to build angular custom modal

Source Code

Source Code

 

 

 

陳建融 Randy Chen