Certificado

Modal en Angular 9 desce cero




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 modalsany[] = [];

    add(modalany) {
        // add modal to array of active modals
        this.modals.push(modal);
    }

    remove(idstring) {
        // remove modal from array of active modals
        this.modals = this.modals.filter(x => x.id !== id);
    }

    open(idstring) {
        // open modal specified by id
        const modal = this.modals.find(x => x.id === id);
        modal.open();
    }

    close(idstring) {
        // 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 { ComponentViewEncapsulationElementRefInputOnInitOnDestroy } 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 OnInitOnDestroy {
    @Input() idstring;
    private elementany;

    constructor(private modalServiceModalServiceprivate elElementRef) {
        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 */
    displaynone;

    .jw-modal {
        /* modal container fixed across whole screen */
        positionfixed;
        top90px;
        right30px;
        bottom0;
        left60px;

        /* z-index must be higher than .jw-modal-background */
        z-index1000;
        
        /* enables scrolling for tall modals */
        overflowauto;

        .jw-modal-body {
            padding20px;
            background#fff;

            /* margin exposes part of the modal background */
            margin40px;
        }
    }

    .jw-modal-background {
        /* modal background fixed across whole screen */
        positionfixed;
        top0;
        right0;
        bottom0;
        left0;

        /* semi-transparent black  */
        background-color#000;
        opacity0.75;
        
        /* z-index must be below .jw-modal and above everything else  */
        z-index900;
    }
}

body.jw-modal-open {
    /* body overflow is hidden to hide main scrollbar when modal window is open */
    overflowhidden;
}


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 { ComponentAfterViewInitInput } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { ModalService } from '../../_modal';

y agregar la referencia en el constructor

constructor(private modalServiceModalServicehttp:HttpClient) { }

adicional agregar los metodos para abrir y cerrar el modal

  openModal(idstring) {
    this.modalService.open(id);
  }

  closeModal(idstring) {
    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

Entradas populares