Contexto
Estoy realizando una migración de de front a angular de un proyecto algo amplío, y dentro de las migraciones, se requiere enviar notificaciones a pantalla. Pero las notificaciones deben ser no intrusivas que necesiten forzosamente la intervención del usuario, ya sea mediante click o esc. En la anterior plataforma se usó un sistema de notificaciones de desarrollado con jquery y bootstrap, por lo que se migró de una manera similar a éste nuevo proyecto.
Y me dispuse a compartir dichas notificaciones, por si alguno requiere notificaciones poco invasivas en la pantalla para el usuario.
Requerimientos
- Angular v18
- Node v22
- Bootstrap v5
- Bootstrap Icons v1
- VsCode
Proyecto Angular
El proyecto a crear y desarrollar se llamará ng-bs-notify si no desean realizar el paso a paso, pueden clonarlo de: https://gitlab.com/linuxitos/notify-bootstrap-angular
Crear proyecto y añadir dependencias
ng new ng-bs-notify
Elegir las opciones por defecto que muestre en pantalla:
Una vez que termine, instalar las dependencias, pueden cambiarlo, y usar tailwind, o css puro:
npm install bootstrap bootstrap-icons
Añadir las rutas de los css de bootstrap, en el archivo angular.json
Buscar la sección de style, para los css:
"styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/bootstrap-icons/font/bootstrap-icons.css", "src/styles.css" ]
Los archivos js en:
"scripts": [ "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js" ]
Crear servicio Alert
El servicio alert.service.ts se encargará de procesar las notificaciones desde cualquier parte del proyecto y mostrarlas en pantalla.
Para crear el servicio, se usa el siguiente comando, dentro directo de app, y dentro del directorio services, usar el siguiente comando:
ng g service services/alert
Una vez creado deberá aparecer de la siguiente manera:
Editar el servicio alert.service.ts
Abrir el archivo alert.service.ts y añadir el siguiente código. Guardar los cambios y listo.
import { Injectable } from '@angular/core' import { Subject } from 'rxjs' export type AlertType = 'success' | 'danger' | 'info' | 'warning' export interface Alert { message: string type: AlertType id: number show: boolean } @Injectable({ providedIn: 'root' }) export class AlertService { private alertsSubject = new Subject(); alerts$ = this.alertsSubject.asObservable(); private alerts: Alert[] = []; private idCounter = 0; showAlert(message: string, type: AlertType) { const alert: Alert = { message, type, id: this.idCounter++, show: false } this.alerts = [alert, ...this.alerts] this.alertsSubject.next(this.alerts) setTimeout(() => { alert.show = true this.alertsSubject.next(this.alerts) }, 10) // Pequeño retraso para activar la animación de fade-in setTimeout(() => { this.fadeOutAlert(alert.id) }, 4000) // Iniciar desvanecimiento después de 3 segundos } fadeOutAlert(id: number) { const alert = this.alerts.find(alert => alert.id === id) if (alert) { alert.show = false this.alertsSubject.next(this.alerts) setTimeout(() => { this.removeAlert(id) }, 500) // Tiempo para la animación de desvanecimiento } } removeAlert(id: number) { this.alerts = this.alerts.filter(alert => alert.id !== id) this.alertsSubject.next(this.alerts) } }
Crear component alert.component.ts
El componente alert.coponent.ts contiene el código, y vistas que se usará para las notificaciones, ésta a su vez los tomará el servicio alert.service.ts
Usar el comando siguiente para crear el componente, y se creará en la ruta app/components
ng g component components/alert
Y se generará de la siguiente manera:
Editar el component Alert
Abrir el archivo alert.component.ts y añadir el siguiente código:
import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { AlertService, Alert } from '../../services/alert.service' import { CommonModule } from '@angular/common'; @Component({ selector: 'app-alert', standalone: true, imports: [RouterOutlet, AlertComponent,CommonModule], templateUrl: './alert.component.html', styleUrl: './alert.component.css' }) export class AlertComponent { alerts: Alert[] = []; show: boolean = false; constructor(private alertService: AlertService) { } ngOnInit(): void { this.alertService.alerts$.subscribe(alerts => { this.alerts = alerts }) } getIcon(type: string): string { switch (type) { case 'danger': return 'bi bi-x-circle' case 'info': return 'bi bi-info-circle' case 'success': return 'bi bi-check-circle' case 'warning': return 'bi bi-exclamation-circle' default: return '' } } closeAlert(id: number) { this.alertService.removeAlert(id) } }
Abrir el archivo alert.component.html
@for (alert of alerts; track alert) {
<div [className]="'alert alert-notify alert-dismissible fade show col-xl-8 col-lg-8 col-md-7 col-sm-8 col-10 alert-'+alert.type"
role="alert" [class]="{'show': alert.show, 'fade-out': !alert.show}">
<div class="w-100">
<i [class]="getIcon(alert.type)"></i> {{alert.message }}
</div>
<button type="button" class="btn-close" (click)="closeAlert(alert.id)" aria-label="Close"></button>
</div>
}
</div>
Abrir el archivo alert.component.css
.alert-container {
position: fixed;
top: 20px;
right: 20px;
z-index: 1050;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 0px;
}
.alert {
opacity: 0;
transform: translateY(-20px);
transition: opacity 0.5s ease-out, transform 0.5s ease-out;
}
.alert.show {
opacity: 1;
transform: translateY(0);
}
.alert.fade-out {
opacity: 0;
transform: translateY(-20px);
}
.alert-notify{
padding: 6px 30px 6px 6px;
}
.alert-notify .btn-close{
margin-top: 5px;
padding: 6px;
}
Configurar app.component
Buscar el archivo app.component.ts y modificarlo de la siguiente manera:
import { Component } from ‘@angular/core’; import { AlertService, AlertType } from ‘./services/alert.service’ import { AlertComponent } from ‘./components/alert/alert.component’; import { CommonModule } from ‘@angular/common’; @Component({ selector: ‘app-root’, standalone: true, imports: [AlertComponent,CommonModule], templateUrl: ‘./app.component.html’, styleUrl: ‘./app.component.css’ }) export class AppComponent { title = ‘Notify Bootstrap Style’; message: string = »; show: boolean = false; constructor( private alertService: AlertService ) { } triggerAlert(message: string, type: AlertType) { this.alertService.showAlert(message, type) } }El archivo app.component.html modificarlo de la siguiente manera:
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<app-alert></app-alert>
</div>
<div class="col-lg-9 col-md-8 col-12">
<div class="row">
<div class="col-md-12 justify-content-center text-center">
<img class="img-fluid" src="../assets/images/logo.svg" alt width="72" height="72" />
<h1 class="h3 mb-3 fw-normal">Alertas</h1>
</div>
</div>
<div class="row">
<div class="col-md-12 d-flex justify-content-center">
<button type="button" (click)="triggerAlert('Un tipo de alerta informativa!', 'info')"
class="btn btn-primary">
Alerta <i class="bi bi-eye"></i>
</button>
<button type="button" (click)="triggerAlert('Tipo de alerta o notificación de error', 'danger')"
class="btn btn-danger mx-2">
Alerta <i class="bi bi-eye"></i>
</button>
<button type="button" (click)="triggerAlert('Tipo de alerta de existosa!', 'success')"
class="btn btn-success mx-2">
Alerta <i class="bi bi-eye"></i>
</button>
<button type="button"
(click)="triggerAlert('Tipo de alerta de que algo requiere atención, no a nivel de error!', 'warning')"
class="btn btn-warning">
Alerta <i class="bi bi-eye"></i>
</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="mt-5 mb-3 text-body-secondary text-center"><a href="https://linuxitos.com/"
target="_blank">linuxitos</a> © 2017-2024</p>
</div>
</div>
</div>
</div>
</div>
Archivo style.css el cuál corresponde al archivo principal de todo el proyecto:
.menu-card {
width: 100%;
height: 37px;
background-color: rgba(0, 0, 0, 0.03);
padding-inline: 20px 0px;
}
.btnMenu {
cursor: pointer;
line-height: 35px;
border: 0;
font-size: 0.9rem;
}
.btnMenu:hover {
background-color: white;
}
.active {
color: #CC3333;
background-color: #fff;
font-weight: 700;
border-bottom: 1px solid #CC3333;
}
.active {
color: #CC3333;
background-color: #fff;
font-weight: 700;
border-bottom: 1px solid #CC3333;
}
div.centerTable {
text-align: center;
padding: 10px;
overflow-x:auto;
}
div.centerTable table {
margin: 0 auto;
text-align: left;
}
.color_White {
color: white;
}
.contenedor {
height: 400px;
border-radius: 10px;
border: 1px solid #ced4da;
margin-top: 25px;
margin-bottom: 25px;
}
.prueba1 {
color: white;
}
.colorgenerate, #tablaListado2 thead{
color: white;
background-color: #CC3333;
}
#divCabezero {
background-color: #CC3333;
margin: 0px 0px 20px 0px;
width: 100%;
color: white;
display: flex;
}
#Sucursal {
float:right;
}
#btnNuevo {
cursor: pointer;
}
#ddlConceptos {
cursor: pointer;
}
#add-sku-ubi {
cursor: pointer;
}
.table-responsivee {
height: 400px;
overflow-y: auto;
}
.list-sku {
cursor: pointer;
}
.list-sku:hover {
color: #FFFFFF;
background-color: #000000;
}
#label-nc {
border: 1px solid gray;
height: 221px;
padding: 10px;
}
#label-ne {
border: 1px solid gray;
height: 221px;
padding: 10px;
}
#txtUsuario {
width: 25%;
}
#txtObservaciones {
width: 50%;
}
#rowCargo {
margin-top: 2px;
}
body {
margin-top: 1%;
}
.panel-heading {
padding: 15px 15px;
}
#loadImg {
margin-top: 10%;
margin-left: 42%;
}
#tdetalle {
overflow-y: auto;
height: 100px;
}
.disabledbutton {
pointer-events: none;
opacity: 0.4;
}
.mover-mensajes-info {
transform: translate(0px, 49px);
}
.hidden {
visibility: hidden;
}
.loading {
display: flex;
justify-content: center;
align-items: center;
top: 0;
left: 0;
position: fixed;
z-index: 10000 !important;
padding: 0;
margin: 0;
width: 100%;
height: 100vh;
opacity: 0.2;
background-color: #999988;
}
.imgLoading {
display: flex;
justify-content: center;
align-items: center;
top: 0;
left: 0;
position: fixed;
z-index: 10000 !important;
padding: 0;
margin: 0;
width: 100%;
height: 100vh;
}
.Listado tbody {
display: block;
height: calc(50vh - 1px);
min-height: calc(200px + 1 px);
overflow-Y: scroll;
color: #000;
}
.Listado tr {
display: block;
overflow: hidden;
cursor: pointer;
}
.Listado tbody tr:nth-child(odd) {
background: rgba(0,0,0,.1);
}
.Listado td {
width: 30%;
float: left;
}
.Listado th {
width: 30%;
float: left;
}
.Listado td {
padding: .1rem 0 .1em 1rem;
border-right: 2px solid rgba(0,0,0,.2);
}
.Listado th:last-child {
width: 70%;
text-align: center;
border-right: 0 none;
padding-left: 0;
}
.Listado td:last-child {
width: 70%;
text-align: center;
border-right: 0 none;
padding-left: 0;
}
.spin-10x {
width: 10rem;
height: 10rem;
}
.spin-10x {
width: 10rem;
height: 10rem;
}
.spin-10x {
width: 10rem;
height: 10rem;
}
.spin-13x {
width: 13rem;
height: 13rem;
}
.bg-ekt {
background-color: #CC3333;
}
[class*="swal-button--"] {
background-color: #0d6efd;
border: 1px solid #0d6efd;
text-shadow: none;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
}
[class*="swal-button--"]:hover, [class*="swal-button--"]:active {
background-color: #0b5ed7 !important;
border: 1px solid #0b5ed7;
text-shadow: none;
color: #fff;
}
.swal-button {
box-shadow: none;
text-shadow: none;
}
.swal-text {
color:#212529;
}
.swal-button--confirm {
background-color: #0d6efd;
border: 1px solid #0d6efd;
text-shadow: none;
}
.swal-button--cancel {
background-color: #dc3545;
border: 1px solid #dc3545;
text-shadow: none;
color: #fff;
}
.swal-button--defeat {
background-color: #6c757d;
border: 1px solid #6c757d;
text-shadow: none;
color: #fff;
}
.swal-button--catch {
background-color: #198754;
border: 1px solid #198754;
text-shadow: none;
color: #fff;
}
.swal-button--catch:hover, .swal-button--catch:active {
background-color: #157347 !important;
border: 1px solid #157347;
text-shadow: none;
color: #fff;
}
.swal-button--cancel:hover, .swal-button--cancel:active {
background-color: #bb2d3b !important;
border: 1px solid #bb2d3b;
text-shadow: none;
color: #fff;
}
.swal-button--defeat:hover, .swal-button--defeat:active {
background-color: #5c636a !important;
border: 1px solid #5c636a;
text-shadow: none;
color: #fff;
}
.swal-button--confirm:hover, .swal-button--confirm:active {
background-color: #0b5ed7 !important;
border: 1px solid #0b5ed7;
text-shadow: none;
color: #fff;
}
.btn-block {
display: block;
width: 100%;
}
.swal-modal-md {
width: 700px;
}
.form-control:focus {
box-shadow: none;
}
/** float label inputs **/
.has-float-label {
position: relative;
width: 100%;
display:inline;
}
.has-float-label label {
position: absolute;
left: 0;
top: 0;
cursor: text;
font-size: 75%;
opacity: 1;
-webkit-transition: all .2s;
transition: all .2s;
top: -.5em;
left: 12px;
z-index: 3;
line-height: 1;
padding: 0 1px;
}
.has-float-label label::after {
content: " ";
display: block;
position: absolute;
background: white;
height: 2px;
top: 50%;
left: -.2em;
right: -.2em;
z-index: -1;
}
.has-float-label .form-control::-webkit-input-placeholder {
opacity: 1;
-webkit-transition: all .2s;
transition: all .2s;
}
.has-float-label .form-control:placeholder-shown:not(:focus)::-webkit-input-placeholder {
opacity: 0;
}
.has-float-label .form-control:placeholder-shown:not(:focus) + label {
opacity: .5;
top: .3em;
font-weight: normal;
}
.input-group .has-float-label {
display: table-cell;
}
.input-group .has-float-label .form-control {
border-radius: 4px;
}
.input-group .has-float-label:not(:last-child) .form-control {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.input-group .has-float-label:not(:first-child) .form-control {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
margin-left: -1px;
}
.has-float-label input:focus, .has-float-label textarea:focus, .has-float-label select:focus {
border-color: #0d47a1;
box-shadow: none;
}
.has-float-label .form-control:placeholder-shown:not(:focus) + * {
font-size: 100%;
margin-top: 4px;
}
.form-icon {
position: absolute;
top: 0;
right: 0;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
pointer-events: none;
margin-right: 5px;
}
.table > tbody > tr > td {
vertical-align: middle;
}
.selectores-format{
text-align: center !important;
}
.txtPedidoGuia {
text-transform: uppercase;
}
.w-5 {
width: 5%;
}
.w-10 {
width: 10%;
}
.w-15 {
width: 15%;
}
.w-20 {
width: 20% !important;
}
.w-30 {
width: 30% !important;
}
.w-40 {
width: 40% !important;
}
.w-50 {
width: 50% !important;
}
.w-60 {
width: 60% !important;
}
.w-70 {
width: 70% !important;
}
.w-80 {
width: 80% !important;
}
.bi-enter {
background: url('data:image/svg+xml;charset=UTF-8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="30" height="30" aria-label="Enter key" class="bi bi-enter" viewBox="0 0 16 16"%3E%3Cg fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2"%3E%3Cpath d="M12 3.53088v3c0 1-1 2-2 2H4M7 11.53088l-3-3 3-3"%3E%3C/path%3E%3C/g%3E%3C/svg%3E') no-repeat;
}
.bi {
display: inline-block;
vertical-align: -0.125em !important;
fill: currentcolor;
}
.form-icon {
margin-top:2px;
position: absolute;
top: 0;
right: 0;
z-index: 0;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
pointer-events: none;
margin-right: 5px;
}
Ejecución del proyecto
Finalmente ejecutar el siguiente comando para lanzar la aplicación y luego abrir desde el navegador con la url http://localhost:4200/.
ng serve
Deberá mostrar algo similar:
Si por alguna razón no les funciona, pueden dejar su comentario, o bien clonar el proyecto desde aquí: https://gitlab.com/linuxitos/notify-bootstrap-angular aquí solo basta clonarlo, instalar dependencias y el comando.