If you're looking to come up with a new approach, remember to close the modal when clicking outside of it.
Building on Luixaviles's solution, the modal component could look something like this:
<div #myModal class="container" (click)="tryClose()">
<div #content class="content">
<ng-content></ng-content>
</div>
</div>
In this setup, the "tryClose" function is triggered when you click on the "myModal" div, checking if the click was not within the "content" section.
tryClose() {
const clickTarget = event.target as HTMLElement;
if (!(this.content.nativeElement as HTMLElement).contains(clickTarget))
this.close();
}
By using <ng-content>
, you can manage the content in the app.component like so:
<app-modal #modal>
<p>Some content here...</p>
<button (click)="modal.close()">Close</button>
</app-modal>
<p>
Open a Modal Using Pure HTML + CSS with Angular
</p>
<button (click)="modal.open()">Open Modal</button>
The functionality in the modal component itself is straightforward:
export class ModalComponent {
@ViewChild("myModal", { static: false }) modal: ElementRef;
@ViewChild("content", { static: false }) content: ElementRef;
open() {
this.modal.nativeElement.style.display = "block";
}
close() {
this.modal.nativeElement.style.display = "none";
}
}
Take a look at Luixaviles's modified version on StackBlitz
Update: Adding a simple stopPropagation makes the process smoother.
<div #myModal class="container" (click)="close()">
<div (click)="$event.stopPropagation()" class="content">
<ng-content></ng-content>
</div>
</div>