If you're looking to grasp the concept of a reusable modal component, I've put together a simplified working version for your understanding. Take a look at the code and feel free to reach out if you encounter any issues. By coding the modal component once, we can effortlessly reuse it across the entire application!
modal component
html
<div
class="modal"
tabindex="-1"
role="dialog"
*ngIf="open"
style="display:block;"
>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ config.title }}</h5>
<button
type="button"
class="close"
data-dismiss="modal"
aria-label="Close"
(click)="discardWrapper($event)"
>
<span aria-hidden="true"gt;×</span>
</button>
</div>
<div class="modal-body">
<p>{{ config.description }}</p>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-primary"
(click)="saveWrapper($event)"
>
Save changes
</button>
<button
type="button"
class="btn btn-secondary"
data-dismiss="modal"
(click)="discardWrapper($event)"
<Close
/button>
/div>
/div>
/div>
/div>
ts
import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { AComponentService } from './a/a.component.service';
export class ModalConfig {
title?: string = '';
description?: string = '';
save?: Function = () => {};
discard?: Function = () => {};
constructor(
title: string = '',
description: string = '',
save = null,
discard = null
) {
if (title) this.title = title;
if (description) this.description = description;
if (save) this.save = save;
if (discard) this.discard = discard;
}
}
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css'],
imports: [CommonModule],
standalone: true,
})
export class ModalComponent implements OnInit {
constructor(private aComponentService: aComponentService) {}
get open() {
return this.aComponentService.isOpen;
}
get config() {
return this.AComponentService.config;
}
...
}
service
import { Injectable } from '@angular/core';
import { ModalConfig } from './modal.component';
@Injectable({
providedIn: 'root',
})
export class AComponentService {
isOpen = false;
configAComponent = new ModalConfig();
constructor() {}
open(config: ModalConfig) {
this.configAComponent = { ...this.configAComponent, ...config };
this.isOpen = true;
}
}
A component using this logic
ts
import { Component, OnInit } from '@angular/core';
import { AComponentService } from '../services/a/a.component.service';
@Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.css'],
standalone: true,
})
export class AComponent implements OnInit {
constructor(private aComponentService: aComponentService) {}
ngOnInit() {}
openModal() {
this.aComponentService.open({
title: 'test',
description: 'test description',
});
}
}
html
<p>a works!</p>
<button (click)="openModal()" class="btn btn-primary">open modal</button>
Check out stackblitz