File

src/app/components/layout/modales/modal-producto/modal-producto.component.ts

Implements

OnInit

Metadata

Index

Properties
Methods

Constructor

constructor(fb: FormBuilder, _categoriaServ: CategoriaService, _productoServ: ProductoService, _utilidadServ: UtilidadService, modalActual: MatDialogRef<ModalProductoComponent>, datosProducto: Producto)
Parameters :
Name Type Optional
fb FormBuilder No
_categoriaServ CategoriaService No
_productoServ ProductoService No
_utilidadServ UtilidadService No
modalActual MatDialogRef<ModalProductoComponent> No
datosProducto Producto No

Methods

guardarEditarProducto
guardarEditarProducto()
Returns : void
ngOnInit
ngOnInit()
Returns : void

Properties

botonAccion
Type : string
Default value : 'Guardar'
Public datosProducto
Type : Producto
Decorators :
@Inject(MAT_DIALOG_DATA)
formularioProducto
Type : FormGroup
listaCategorias
Type : Categoria[]
Default value : []
tituloAccion
Type : string
Default value : 'Agregar'
import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Categoria } from 'src/app/interfaces/categoria';
import { Producto } from 'src/app/interfaces/producto';
import { CategoriaService } from 'src/app/services/categoria.service';
import { ProductoService } from 'src/app/services/producto.service';
import { UtilidadService } from 'src/app/shared/utilidad.service';

@Component({
  selector: 'app-modal-producto',
  templateUrl: './modal-producto.component.html',
  styleUrls: ['./modal-producto.component.css']
})
export class ModalProductoComponent implements OnInit{

  formularioProducto: FormGroup;
  tituloAccion: string = 'Agregar';
  botonAccion: string = 'Guardar';
  listaCategorias: Categoria[] = [];

  constructor(
    private fb: FormBuilder,
    private _categoriaServ: CategoriaService,
    private _productoServ: ProductoService,
    private _utilidadServ: UtilidadService,
    private modalActual: MatDialogRef<ModalProductoComponent>,
    @Inject(MAT_DIALOG_DATA) public datosProducto: Producto) {
      this.formularioProducto = this.fb.group({
        nombre: ['', Validators.required],
        idCategoria: ['', Validators.required],
        stock: ['', Validators.required],
        precio: ['', Validators.required],
        esActivo: ['1', Validators.required]
      });

      if(this.datosProducto != null){
        this.tituloAccion = 'Editar';
        this.botonAccion = 'Actualizar';
      }
      this._categoriaServ.lista().subscribe({
        next: (data) => {
            if(data.status) this.listaCategorias = data.value
        },
        error: (err) => {}
      });
    }

  ngOnInit(): void {
    if(this.datosProducto != null){
      this.formularioProducto.patchValue({
        nombre: this.datosProducto.nombre,
        idCategoria: this.datosProducto.idCategoria,
        stock: this.datosProducto.stock,
        precio: this.datosProducto.precio,
        esActivo: this.datosProducto.esActivo.toString()
      });
    }
  }

  guardarEditarProducto(){
    const _producto: Producto = {
      idProducto: this.datosProducto == null ? 0 : this.datosProducto.idProducto,
      nombre:  this.formularioProducto.value.nombre,
      idCategoria:  this.formularioProducto.value.idCategoria,
      descripcionCategoria:  '',
      stock:  this.formularioProducto.value.stock,
      precio:  this.formularioProducto.value.precio,
      esActivo:  parseInt(this.formularioProducto.value.esActivo)
    };
    if(this.datosProducto == null){
      this._productoServ.guardar(_producto).subscribe({
        next: (data) => {
          if(data.status){
            this._utilidadServ.mostrarAlerta('El producto fue registrado correctamente', 'Ok ✔️')
            this.modalActual.close('true');
          }else{
            this._utilidadServ.mostrarAlerta('No se pudo registrar el producto. Por favor intente de nuevo.', 'Opps! ❌');
          }
        },
        error: (err) => { 
          this._utilidadServ.mostrarAlerta(`Ah ocurrido un error inesperado: ${err.message}`, 'Opps! ❌');
         }
      });
    }else{
      this._productoServ.editar(_producto).subscribe({
        next: (data) => {
          if(data.status){
            this._utilidadServ.mostrarAlerta('El producto fue editado correctamente', 'Ok ✔️')
            this.modalActual.close('true');
          }else{
            this._utilidadServ.mostrarAlerta('No se pudo editar el producto. Por favor intente de nuevo.', 'Opps! ❌');
          }
        },
        error: (err) => { 
          this._utilidadServ.mostrarAlerta(`Ah ocurrido un error inesperado: ${err.message}`, 'Opps! ❌');
         }
      });
    }
  }
}
<h2 mat-dialog-title>{{tituloAccion}} Producto</h2>
<mat-dialog-content>
    <form [formGroup]="formularioProducto">
        <mat-grid-list cols="1" rowHeight="80px">
            <mat-grid-tile>
                <mat-form-field appearance="fill">
                    <mat-label>Nombre</mat-label>
                    <input matInput autocomplete="off" formControlName="nombre" placeholder="Ingresa el nombre del producto">
                    <mat-icon matSuffix>fit_screen</mat-icon>
                </mat-form-field>
            </mat-grid-tile>
            <mat-grid-tile>
                <mat-form-field appearance="fill">
                    <mat-label>Categoria</mat-label>
                    <mat-select formControlName="idCategoria">
                        <mat-option *ngFor="let item of listaCategorias" [value]="item.idCategoria">{{item.nombre}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-grid-tile>
            <mat-grid-tile>
                <mat-form-field appearance="fill">
                    <mat-label>Stock</mat-label>
                    <input type="number" matInput autocomplete="off" formControlName="stock" placeholder="Ingresa el stock del producto">
                    <mat-icon matSuffix>edit_square</mat-icon>
                </mat-form-field>
            </mat-grid-tile>
            <mat-grid-tile>
                <mat-form-field appearance="fill">
                    <mat-label>Precio</mat-label>
                    <input matInput autocomplete="off" formControlName="precio" placeholder="Ingresa el precio del producto">
                    <mat-icon matSuffix>attach_money</mat-icon>
                </mat-form-field>
            </mat-grid-tile>
            <mat-grid-tile>
                <mat-form-field appearance="fill">
                    <mat-label>Estado</mat-label>
                    <mat-select formControlName="esActivo">
                        <mat-option value="1">Activo</mat-option>
                        <mat-option value="0">No activo</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-grid-tile>
        </mat-grid-list>
    </form>
</mat-dialog-content>
<mat-dialog-actions align="end">
    <button mat-raised-button mat-dialog-close color="warn">Volver</button>
    <button mat-raised-button color="primary" [disabled]="formularioProducto.invalid" (click)="guardarEditarProducto()">{{botonAccion}}</button>
</mat-dialog-actions>

./modal-producto.component.css

mat-form-field{
    width: 100%;
    margin: 10px 10px;
}

form{
    width: 350px;
}
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""