Para desarrollar un modal, con caracteristicas personalizadas, y despues de tanto buscar en la web, basandome en un código preexistente en la web logre montar en mi proyecto un modal el cual pude personalizar a gusto.
Directorio de archivos necesarios
Lo primero es crear el archivo
index.ts, el cual contendrá lo siguiente:
export * from './modal.module';
export * from './modal.service';
Luego creamos modal.service.ts el cual contiene los eventos (crear, abrir, cerrar) de modal
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ModalService {
private modals: any[] = [];
add(modal: any) {
// add modal to array of active modals
this.modals.push(modal);
}
remove(id: string) {
// remove modal from array of active modals
this.modals = this.modals.filter(x => x.id !== id);
}
open(id: string) {
// open modal specified by id
const modal = this.modals.find(x => x.id === id);
modal.open();
}
close(id: string) {
// close modal specified by id
const modal = this.modals.find(x => x.id === id);
modal.close();
}
}
Crear el archivo modal.component.ts en este se agrega modal.service.ts y se desglosan las acciones de los eventos y acciones de la ventana modal.
import { Component, ViewEncapsulation, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
import { ModalService } from './modal.service';
@Component({
selector: 'jw-modal',
templateUrl: 'modal.component.html',
styleUrls: ['modal.component.less'],
encapsulation: ViewEncapsulation.None
})
export class ModalComponent implements OnInit, OnDestroy {
@Input() id: string;
private element: any;
constructor(private modalService: ModalService, private el: ElementRef) {
this.element = el.nativeElement;
}
ngOnInit(): void {
// ensure id attribute exists
if (!this.id) {
console.error('modal must have an id');
return;
}
// move element to bottom of page (just before </body>) so it can be displayed above everything else
document.body.appendChild(this.element);
// close modal on background click
this.element.addEventListener('click', el => {
if (el.target.className === 'jw-modal') {
this.close();
}
});
// add self (this modal instance) to the modal service so it's accessible from controllers
this.modalService.add(this);
}
// remove self from modal service when component is destroyed
ngOnDestroy(): void {
this.modalService.remove(this.id);
this.element.remove();
}
// open modal
open(): void {
this.element.style.display = 'block';
document.body.classList.add('jw-modal-open');
}
// close modal
close(): void {
this.element.style.display = 'none';
document.body.classList.remove('jw-modal-open');
}
}
Ahora se crea el archivo modal.module.ts en el cual agregamos el componente modal.component.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModalComponent } from './modal.component';
@NgModule({
imports: [CommonModule],
declarations: [ModalComponent],
exports: [ModalComponent]
})
export class ModalModule { }
Finamente se crea el archivo modal.component.less
jw-modal {
/* modals are hidden by default */
display: none;
.jw-modal {
/* modal container fixed across whole screen */
position: fixed;
top: 90px;
right: 30px;
bottom: 0;
left: 60px;
/* z-index must be higher than .jw-modal-background */
z-index: 1000;
/* enables scrolling for tall modals */
overflow: auto;
.jw-modal-body {
padding: 20px;
background: #fff;
/* margin exposes part of the modal background */
margin: 40px;
}
}
.jw-modal-background {
/* modal background fixed across whole screen */
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
/* semi-transparent black */
background-color: #000;
opacity: 0.75;
/* z-index must be below .jw-modal and above everything else */
z-index: 900;
}
}
body.jw-modal-open {
/* body overflow is hidden to hide main scrollbar when modal window is open */
overflow: hidden;
}
Finalmente la implementación:
1. Agregar el componente en app.module.ts para que sea reconocido en cualquierparte del código.
import { ModalModule } from './_modal';
2. Agregar el componente en el Ejemplo.module.ts
import { ModalModule } from '../../_modal';
3. Igualmente agregar en el Component Ejemplo.component.ts
import { Component, AfterViewInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { ModalService } from '../../_modal';
y agregar la referencia en el constructor
constructor(private modalService: ModalService, http:HttpClient) { }
adicional agregar los metodos para abrir y cerrar el modal
openModal(id: string) {
this.modalService.open(id);
}
closeModal(id: string) {
this.modalService.close(id);
}
y agregar en el html la llamada al modal.
<jw-modal id="mymodal">
<h1 style="height:100px">A Tall Custom Modal!</h1>
<button (click)="closeModal('mymodal');">Close</button>
</jw-modal>
solo debe indicar a la variable modalService que desea abrir el modal
this.modalService.open('mymodal');
Comentarios