# Modal Component and Service
# modal.service.ts
export class ModalService {
private showModal: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
getShowModal(): Observable<boolean> {
return this.showModal.asObservable();
}
openModal(): void {
this.showModal.next(true);
}
closeModal(): void {
this.showModal.next(false);
}
}
# modal.component.ts
export class ModalComponent implements OnInit {
showModal: boolean = false;
constructor(private modalService: ModalService) { }
ngOnInit() {
this.modalService.getShowModal().subscribe(showModal => {
this.showModal = showModal;
});
}
closeModal(): void {
this.modalService.closeModal();
}
}
# modal.component.html
<div class="modal" *ngIf="showModal">
<div>
<ng-content></ng-content>
</div>
<div>
<button class="btn btn-primary" (click)="closeModal()">Close</button>
</div>
</div>
# app.component.html
<app-modal>
<h1>Modal Header</h1>
<p>Some text in the Modal Body</p>
</app-modal>
# app.component.ts
export class AppComponent implements OnInit {
constructor(private modalService: ModalService) { }
ngOnInit() {
this.modalService.openModal();
}
}