I have a problem with my angular project, I want to make a drop list in which it shows me all the options that a field of a table in my database gives me, but I don't know how to apply it, to explain myself better, I add a reference image of what I want to do
The detail is that what I want to do is implement this drop list but dynamically, so that I get the data that is inside a field in a table (connection to the base and api already made) according to seeing the codes, it is done in this way way:
import { Component } from '@angular/core';
@Component({
// tslint:disable-next-line:component-selector
selector: 'app-dropdown-sample-1',
styleUrls: ['./dropdown-sample-1.component.scss'],
templateUrl: './dropdown-sample-1.component.html'
})
export class DropDownSample1Component {
public items: { field: string }[] = [
{ field: 'Option 1' },
{ field: 'Option 2' },
{ field: 'Option 3' }
];
}
.button {
margin: 8px;
width: 128px;
}
<button class="button" igxButton="raised" [igxToggleAction]="dropdown"
[igxDropDownItemNavigation]="dropdown">Options</button>
<igx-drop-down #dropdown>
<igx-drop-down-item *ngFor="let item of items">
{{ item.field }}
</igx-drop-down-item>
</igx-drop-down>
As I said before, I don't know how I could apply this code to what I'm looking for or if there is an easier way (I share the code of how it is structured so far without adding the method)
import { Component, OnInit } from '@angular/core';
//import { NgForm } from '@angular/forms';
import { Modelo } from '../models/modelo.model';
import {ApiDataService} from './../services/api-data.service';
import { DocumentDefinition, PdfMakeWrapper, Table } from 'pdfmake-wrapper';
import * as pdfFonts from 'pdfmake/build/vfs_fonts';
import * as pdfMake from 'pdfmake/build/pdfmake';
import { muestreomodel } from '../models/muestreo.model';
PdfMakeWrapper.setFonts(pdfFonts);
const pdf = new PdfMakeWrapper();
@Component({
selector: 'app-empleado',
templateUrl: './empleado.component.html',
styleUrls: ['./empleado.component.css']
})
export class EmpleadoComponent implements OnInit {
//IMPORTA EL MODELO PARA IMPORTAR EL LOS CAMPOS QUE SE UTILIZARÁN
modelo = new Modelo();
//DEFINIENDO ELEMENTOS PARA INGRESAR Y LEER DATOS
public allPersons : any;
private data: any;
public allAfp : any;
public Muestreoall: any;
/*Muestreo(){
return this._api.Muestreo().subscribe((data)=>{
this.data = data;
this.Muestreoall = this.data.afp2;
})
}
*/
//IMPORTACIÓN DE LA API PARA UTILIZAR LA CONEXIÓN DEL BACKEND AL FRONTEND
constructor( private _api: ApiDataService) { }
ngOnInit() {
// MUESTRA LOS DATOS EN PANTALLA
return this._api.MuestraAFP().subscribe((data)=>{
this.data = data;
this.allAfp = this.data.afps;
});
}
// FUNCIÓN QUE PERMITE INGRESAR DATOS
ingresoEmpleados(){
return this._api.getInsertEmpleados(this.modelo).subscribe((data:any)=>{
// CONDICIONAL POR SI LOS DATOS INGRESADOS SON SIMILARES AL CODIGO DE IDENTIFICACIÓN
//SI LA SENTENCIA NO ES CIERTA, PROCEDERÁ A INGRESAR LA INFORMACIÓN A LA BASE
this.allAfp = [...this.allAfp, {...this.modelo}].sort((a, b) => a.COD_CIA - b.COD_CIA);
})
}
// FUNCIÓN QUE PERMITE ACTUALIZAR DATOS
ActualizarEmpleados(){
/*POR MEDIO DE ESTA SENTENCIA DE CODIGO LE DIGO A MI PROGRAMA QUE CUANDO MANDE LA ACTUALIZACIÓN POR MEDIO DEL BOTÓN "EDITAR" SE HAGA
UN EVENTO QUE LOGRE CONECTAR CON LA BASE Y ACTUALICE LOS DATOS POR MEDIO DEL ID QUE SERÁ EL IDENTIFICADOR PARA SABER QUE DATOS SE ACTUALIZARÁN*/
return this._api.putUpdateEmpleados(this.modelo).subscribe((data:any)=>{
this.allAfp = [...this.allAfp].map((item) => {
if (item.COD_CIA == data.data.COD_CIA) {
return data.data;
}
return item;
})
})
}
/* FUNCIÓN QUE ME PERMITE POR MEDIO DE UN EVENTO LLAMADO "(click)="EliminarEmpleado(p.COD_CIA)" DE PARTE DEL HTML
MANDAR UNA PETICIÓN AUTOMÁTICA PARA ELIMINAR LOS DATOS SIN NECESIDAD DE LLENAR UN FORMULARIO
*/
EliminarEmpleado(COD_CIA: any){
return this._api.DeleteEmpleados(COD_CIA).subscribe((data:any)=>{
this.allAfp = [...this.allAfp].filter(
(item) => item.COD_CIA != data.data.COD_CIA
);
})
}
//por medio de un evento "(click)" proveniente del html, logro capturar los datos y mostrarlos en pdf
Generarpdf(empleado:any){
//constante que me permite generar el esquema de la tabla con la información de la base
const tabla = new Table([
['COD_CIA', 'Primer nombre', 'Segundo Nombre', 'Primer Apellido', 'Segundo Apellido'],
[empleado.COD_CIA, empleado.PRIMER_NOMBRE, empleado.SEGUNDO_NOMBRE, empleado.PRIMER_APELLIDO, empleado.SEGUNDO_APELLIDO],
]).end;
//inicializador del pdf
const pdf = new PdfMakeWrapper();
pdf.add( tabla);
pdf.create().open();
pdf.create().download();
//pdfMake.createPdf(tabla).download();
console.log(pdf)
console.log(empleado);
return empleado;
}
}
.titulo {
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<h1>EMPLEADOS</h1>
<hr>
<div class="container">
<div class="row ">
<div class="col ">
<!--BOTÓN PARA ABRIR UN MODAL Y POR MEDIO DE ESE MODAL, INGRESAR LA INFORMACIÓN QUE SE SOLICITA PARA INGRESARLA A LA BASE DE DATOS-->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
<i class="fa-solid fa-plus"> Agregar</i>
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Ingresa Los datos </h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<!--FORM-->
<!--LA ETIQUETA FORM Y LA FUNCIÓN "(ngSubmit)="ingresoEmpleados()"" ME PERMITEN PODER ENVIAR LOS DATOS A LA FUNCION DE MI
COMPONENTE PARA QUE ESTE LOS LEA Y LA BASE LOS ATRAPE-->
<form (ngSubmit)="ingresoEmpleados()">
<div class="form-floating mb-3">
<input type="email" class="form-control" id="floatingInput" [(ngModel)]="modelo.COD_CIA" name="COD_CIA" placeholder="[email protected]">
<label for="floatingPassword">COD_CIA</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" [(ngModel)]="modelo.COD_NEGOCIO" name="COD_NEGOCIO" placeholder="">
<label for="floatingPassword">COD_NEGOCIO</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" [(ngModel)]="modelo.COD_EMPLEADO" name="COD_EMPLEADO" placeholder="in">
<label for="floatingPassword">COD_EMPLEADO</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" [(ngModel)]="modelo.PRIMER_NOMBRE" name="PRIMER_NOMBRE" placeholder="Password">
<label for="floatingPassword">PRIMER NOMBRE</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" [(ngModel)]="modelo.SEGUNDO_NOMBRE" name="SEGUNDO_NOMBRE" placeholder="Password">
<label for="floatingPassword">SEGUNDO_NOMBRE</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" [(ngModel)]="modelo.PRIMER_APELLIDO" name="PRIMER_APELLIDO" placeholder="Password">
<label for="floatingPassword">PRIMER_APELLIDO</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" [(ngModel)]="modelo.SEGUNDO_APELLIDO" name="SEGUNDO_APELLIDO" placeholder="Password">
<label for="floatingPassword">SEGUNDO_APELLIDO</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" [(ngModel)]="modelo.FECHA_NACIMIENTO" name="FECHA_NACIMIENTO" placeholder="Password">
<label for="floatingPassword">Fecha de nacimiento</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" [(ngModel)]="modelo.COD_AFP" name="COD_AFP" placeholder="Password">
<label for="floatingPassword">COD_AFP</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.DUI " name="DUI " placeholder="Password ">
<label for="floatingPassword ">DUI</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.NIT " name="NIT " placeholder="Password ">
<label for="floatingPassword ">NIT</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.COD_UNIDAD " name="COD_UNIDAD " placeholder="Password ">
<label for="floatingPassword ">UNIDAD</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.COD_LABORAL " name="COD_LABORAL " placeholder="Password ">
<label for="floatingPassword ">Codigo Laboral</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.COD_SUCURSAL " name="COD_SUCURSAL " placeholder="Password ">
<label for="floatingPassword ">Codigo Sucursal</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.SALARIO_REFERENCIA " name="SALARIO_REFERENCIA " placeholder="Password ">
<label for="floatingPassword ">Salario Referencia</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.COD_BANCO " name="COD_BANCO " placeholder="Password ">
<label for="floatingPassword ">Banco</label>
</div>
<div class="modal-footer ">
<button type="button " class="btn btn-secondary " data-bs-dismiss="modal ">Cerrar</button>
<!--EL BOTÓN SUBMIT HACE QUE TODA LA INFORMACIÓN QUE YO AGREGUE SEA LEÍDA POR LA FUNCION QUE TIENE LA ETIQUETE FORM
Y ESTA INFO SE INTEGRE A LA BASE DE DATOS-->
<button type="submit " class="btn btn-primary ">Añadir</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!--TABLA QUE ME PERMITE MOSTRAR DATOS-->
<table class="table mt-3 ">
<thead class="table-dark ">
<tr>
<th scope="col ">Cod_cia</th>
<th scope="col ">Primer nombre</th>
<th scope="col ">Segundo Nombre</th>
<th scope="col ">Primer apellido</th>
<th scope="col ">Segundo apellido</th>
<th scope="col ">Fecha de nacimiento</th>
<th scope="col ">Labor</th>
<th scope="col ">AFP</th>
<th scope="col ">Banco</th>
<th scope="col ">Editar</th>
<th scope="col ">Eliminar</th>
<th scope="col ">PDF</th>
<th scope="col "></th>
</tr>
</thead>
<tbody class="table-group-divider ">
<!--POR MEDIO DEL *NGFOR, PUEDO LOGRAR QUE MIS DATOS PUEDAN MOSTRARSE POR MEDIO DE UNA VARIABLE,
Y TRAER LOS CAMPOS QUE YO QUIERA MOSTRAR-->
<tr *ngFor="let p of allAfp ">
<th scope="row ">{{p.COD_CIA}}</th>
<th scope="row ">{{p.PRIMER_NOMBRE}}</th>
<th scope="row ">{{p.SEGUNDO_NOMBRE}}</th>
<th scope="row ">{{p.PRIMER_APELLIDO}}</th>
<th scope="row ">{{p.SEGUNDO_APELLIDO}}</th>
<th scope="row ">{{p.FECHA_NACIMIENTO}}</th>
<th scope="row ">{{p.DESCRIPCION_1}}</th>
<th scope="row ">{{p.DESCRIPCION}}</th>
<th scope="row ">{{p.BANCODESC}}</th>
<!--MODAL PARA EDITAR DATOS-->
<th scope="row "> <button type="button " class="btn btn-primary " data-bs-toggle="modal " data-bs-target="#staticBackdrop ">
<i class="fa-solid fa-pencil "></i>
</button>
<!--ES IGUAL QUE EL AGREGAR DATOS, LO UNICO QUE CAMBIA SON UNAS FRASES Y LAS FUNCIONES DENTRO DEL BACKEND-->
<!-- Modal -->
<div class="modal fade " id="staticBackdrop " data-bs-backdrop="static " data-bs-keyboard="false " tabindex="-1 " aria-labelledby="staticBackdropLabel " aria-hidden="true ">
<div class="modal-dialog ">
<div class="modal-content ">
<div class="modal-header ">
<h5 class="modal-title " id="staticBackdropLabel ">Editar datos</h5>
<button type="button " class="btn-close " data-bs-dismiss="modal " aria-label="Close "></button>
</div>
<div class="modal-body ">
<form (ngSubmit)="ActualizarEmpleados() ">
<div class="form-floating mb-3 ">
<input type="email " class="form-control " id="floatingInput " [(ngModel)]="modelo.COD_CIA " name="COD_CIA " placeholder="[email protected] ">
<label for="floatingPassword ">COD_CIA</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.COD_NEGOCIO " name="COD_NEGOCIO " placeholder="COD_NEGOCIO ">
<label for="floatingPassword ">COD_NEGOCIO</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.COD_EMPLEADO " name="COD_EMPLEADO " placeholder="COD_EMPLEADO ">
<label for="floatingPassword ">COD_EMPLEADO</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.PRIMER_NOMBRE " name="PRIMER_NOMBRE " placeholder="PRIMER_NOMBRE ">
<label for="floatingPassword ">PRIMER NOMBRE</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.SEGUNDO_NOMBRE " name="SEGUNDO_NOMBRE " placeholder="SEGUNDO_NOMBRE ">
<label for="floatingPassword ">SEGUNDO_NOMBRE</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.PRIMER_APELLIDO " name="PRIMER_APELLIDO " placeholder="PRIMER_APELLIDO ">
<label for="floatingPassword ">PRIMER_APELLIDO</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.SEGUNDO_APELLIDO " name="SEGUNDO_APELLIDO " placeholder="SEGUNDO_APELLIDO ">
<label for="floatingPassword ">SEGUNDO_APELLIDO</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.COD_AFP " name="COD_AFP " placeholder="COD_AFP ">
<label for="floatingPassword ">COD_AFP</label>
</div>
<div class="form-floating ">
<input type="text " class="form-control " id="floatingInput " [(ngModel)]="modelo.FECHA_NACIMIENTO " name="FECHA_NACIMIENTO " placeholder="Fecha de nacimiento ">
<label for="floatingPassword ">Fecha de nacimiento</label>
</div>
<div class="modal-footer ">
<button type="button " class="btn btn-secondary " data-bs-dismiss="modal ">Cerrar</button>
<button type="submit " class="btn btn-primary ">Editar</button>
</div>
</form>
</div>
</div>
</div>
</div>
</th>
<!--MODAL PARA BORRAR DATOS-->
<th scope="row ">
<!--(click)="EliminarEmpleado(p.COD_CIA) " ES UN EVENTO QUE ME PERMITE BORRAR DATOS SIN LA NECESIDAD DE UN FORMULARIO,
EL PROCESO LO TOMA EL COMPONENTE ELIMINAR EMPLEADO DE EMPLEADO.COMPONENT.TS -->
<button type="button " (click)="EliminarEmpleado(p.COD_CIA) " class="btn btn-danger ">
<i class="fa-solid fa-trash-can "></i>
</button></th>
<th scope="row ">
<button (click)="Generarpdf(p) " type="button " class="btn btn-primary ">
<i class="fa-solid fa-file-pdf "></i>
</button>
</th>
</tr>
</tbody>
</table>
</div>
Revisando tu consulta, puedes realizar lo siguiente. Así como tienes métodos que realizan operaciones con PDF, deberás crear otro métdodo en tu ApiDataService que traiga la lista de opciones para el dropdown.
api-data.service.ts
Después, tendrás que crear una variable que recepcione la información de tu API en EmpleadoComponent. Si lo que deseas es mostrar la información del menú cuando el componente carga por primera vez, debes llamarlo desde el ngOnInit. Te recomiendo revisar el ciclo de vida de un componente en angular.
empleado.component.ts
So, from here you can follow the example you posted by replacing the variable
items
withdropdownData
and using the *ngFor directive you will be able to iterate through the elements of the list.IgxDropDownComponent example
Bootstrap example
common example