En mi proyecto angular tengo un grid designer donde personalizo cada celda con otros componentes.
Necesito que para que funcione correctamente, cuando se activa la multiselección, en el selectedContent se meta el valor del kpi por defecto como un array con label y value de la misma forma que en contentOptions.
import { Component, OnInit, ViewContainerRef, ViewChildren, QueryList, AfterViewInit, NgModule, HostListener, ViewChild, ElementRef,inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerModule, NgxSpinnerService } from 'ngx-spinner';
import * as ace from 'ace-builds';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-dracula';
import { GaugeComponent } from '../gauge/gauge.component';
import { DataGridComponent } from '../data-grid/data-grid.component';
import { KpiListComponent } from '../kpis/kpi-list.component';
import { KpiService } from '../../services/kpi.services'
import { NgSelectModule } from '@ng-select/ng-select';
const data = await this.kpiService.getKPI(kpiRequest).toPromise();
console.log("🔰 ~ loadDynamicComponent ~ data:", data)
let representacion: string | null = null;
if (data.representacion) {
representacion = data.representacion;
}
if (!representacion) {
this.toastr.error(`No se encuentra "representacion" en el json para: ${componentName}`);
throw new Error(`No se encuentra "representacion" en el json para: ${componentName}`);
}
const module = await import(`../kpi-components/kpi-${representacion}/kpi-${representacion}.component`);
return module[`Kpi${this.pascalCase(representacion)}Component`];
}
// convertir a pascalcase el string para que funcione
private pascalCase(str: string): string {
return str.split('-').map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('');
}
toggleSwitch(col: any) {
console.log("🔰 ~ toggleSwitch ~ col:", col)
if (!col.showSwitch) {
col.alternativeContent = null;
}
this.updateJsonAndEditor();
}
toggleMultiSelection(col: any) {
col.multiSelection = !col.multiSelection;
if (col.multiSelection) {
// Aseguramos que col.content es un array y si no, se transforma
if (!Array.isArray(col.content)) {
col.content = col.content ? [col.content] : [];
}
// Actualizamos contentOptions para que tenga solo las opciones seleccionadas
col.contentOptions = this.componentOptions.filter(option => col.content.includes(option.value));
// Ponemos el [0] de selectedContent como el primer KPI seleccionado por defecto
col.selectedContent = col.content[0] || null;
} else {
// // Fuera de multiselección, nos aseguramos de que col.content sea un array con solo un elemento
// if (col.content && col.content.length > 0) {
// col.content = [col.content[0]];
// col.selectedContent = col.content[0];
// } else {
// col.content = [];
// col.selectedContent = null;
// }
// Limpiamos 'contentOptions' ya que no se necesita en modo no multiselección
col.contentOptions = [];
}
console.log("Multiselección ", col);
}
switchComponent(col: any, side: string) {
// Intercambiamos las propiedades relacionadas al contenido principal y alternativo
[col.content, col.alternativeContent] = [col.alternativeContent, col.content];
[col.contentOptions, col.alternativeContentOptions] = [col.alternativeContentOptions, col.contentOptions];
[col.selectedContent, col.alternativeSelectedContent] = [col.alternativeSelectedContent, col.selectedContent];
col.switchActiveSide = side;
// Obtener los índices de la celda
const { rowIndex, colIndex } = this.getCellIndices(col);
// Re-renderizar el componente
this.renderDynamicComponents(rowIndex, colIndex);
// Actualizar el JSON y el editor
this.updateJsonAndEditor();
}
applyKPI() {
if (this.editingCell.content) {
let kpiNumbers = Array.isArray(this.editingCell.content)
? this.editingCell.content
: [this.editingCell.content];
// Convertir a números de KPI
kpiNumbers = kpiNumbers.map((item:any) => this.extractKpiNumber(item.toString()));
this.editingCell.content = kpiNumbers;
if (this.editingCell.multiSelection) {
console.log("ApplyKPI Multiselección");
// Filtrar las opciones seleccionadas para contentOptions
this.editingCell.contentOptions = this.componentOptions.filter(option => this.editingCell.content.includes(option.value));
console.log("🔰 ~ applyKPI ~ this.editingCell.contentOptions:", this.editingCell.contentOptions)
this.editingCell.selectedContent = kpiNumbers[0] || null;
console.log("🔰 ~ applyKPI ~ this.editingCell.selectedContent :", this.editingCell.selectedContent )
} else {
this.editingCell.selectedContent = kpiNumbers[0] || null;
}
}
// Procesar alternativeContent de manera similar
if (this.editingCell.showSwitch && this.editingCell.alternativeContent) {
let altKpiNumbers = Array.isArray(this.editingCell.alternativeContent)
? this.editingCell.alternativeContent
: [this.editingCell.alternativeContent];
// Convertir a números de KPI
altKpiNumbers = altKpiNumbers.map((item: any) => this.extractKpiNumber(item.toString()));
this.editingCell.alternativeContent = altKpiNumbers;
if (this.editingCell.multiSelection) {
// Filtrar las opciones seleccionadas para alternativeContentOptions
this.editingCell.alternativeContentOptions = this.componentOptions.filter(option => this.editingCell.alternativeContent.includes(option.value));
this.editingCell.alternativeSelectedContent = altKpiNumbers[0] || null;
} else {
this.editingCell.alternativeSelectedContent = altKpiNumbers[0] || null;
}
}
this.editingCell.isComponent = true;
// Actualizar gridData y gridDataString
const { rowIndex, colIndex } = this.getEditingCellIndices();
let gridDataStringObj = JSON.parse(this.gridDataString);
gridDataStringObj[rowIndex].columns[colIndex] = {
...gridDataStringObj[rowIndex].columns[colIndex],
...this.editingCell,
};
this.gridDataString = JSON.stringify(gridDataStringObj, null, 2);
this.gridData[rowIndex].columns[colIndex] = gridDataStringObj[rowIndex].columns[colIndex];
this.updateEditorValue();
this.renderDynamicComponents(rowIndex, colIndex);
this.editingCell = null;
}
getEditingCellIndices() {
let rowIndex = -1;
let colIndex = -1;
for (let i = 0; i < this.gridData.length; i++) {
const columns = this.gridData[i].columns;
for (let j = 0; j < columns.length; j++) {
if (columns[j] === this.editingCell) {
rowIndex = i;
colIndex = j;
return { rowIndex, colIndex };
}
}
}
return { rowIndex, colIndex };
}
private extractKpiNumber(value: string | number): number {
if (typeof value === 'number') {
return value;
}
const match = value.match(/\d+/);
return match ? parseInt(match[0], 10) : 0;
}
}
Para lograr que selectedContent contenga el valor del KPI por defecto como un objeto con label y value cuando se activa la multiselección, necesitas modificar algunas partes de tu código donde se asigna selectedContent.
Específicamente, debes modificar las funciones toggleMultiSelection y applyKPI para que asignen el primer elemento de contentOptions a selectedContent en lugar de solo el número del KPI. Esto asegurará que selectedContent tenga el mismo formato que contentOptions.
Aquí están las modificaciones necesarias:
En la función toggleMultiSelection(col: any), cambia la asignación de col.selectedContent para que use el primer elemento de col.contentOptions:
toggleMultiSelection(col: any) {
col.multiSelection = !col.multiSelection;
if (col.multiSelection) {
// Aseguramos que col.content es un array y si no, se transforma
if (!Array.isArray(col.content)) {
col.content = col.content ? [col.content] : [];
}
// Actualizamos contentOptions para que tenga solo las opciones seleccionadas
col.contentOptions = this.componentOptions.filter(option => col.content.includes(option.value));
// Ponemos el primer objeto de selectedContent como el primer KPI seleccionado por defecto
col.selectedContent = col.contentOptions[0] || null;
} else {
// Limpiamos 'contentOptions' ya que no se necesita en modo no multiselección
col.contentOptions = [];
}
console.log("Multiselección ", col);
}
En la función applyKPI(), modifica la asignación de this.editingCell.selectedContent dentro del bloque de multiselección para que también use contentOptions[0]:
if (this.editingCell.multiSelection) {
console.log("ApplyKPI Multiselección");
// Filtrar las opciones seleccionadas para contentOptions
this.editingCell.contentOptions = this.componentOptions.filter(option => this.editingCell.content.includes(option.value));
console.log("🔰 ~ applyKPI ~ this.editingCell.contentOptions:", this.editingCell.contentOptions);
// Asignar el primer objeto de contentOptions a selectedContent
this.editingCell.selectedContent = this.editingCell.contentOptions[0] || null;
console.log("🔰 ~ applyKPI ~ this.editingCell.selectedContent :", this.editingCell.selectedContent);
} else {
this.editingCell.selectedContent = kpiNumbers[0] || null;
}
Si estás manejando alternativeContent en modo de multiselección, también debes ajustar alternativeSelectedContent de manera similar:
if (this.editingCell.multiSelection) {
// Filtrar las opciones seleccionadas para alternativeContentOptions
this.editingCell.alternativeContentOptions = this.componentOptions.filter(option => this.editingCell.alternativeContent.includes(option.value));
// Asignar el primer objeto de alternativeContentOptions a alternativeSelectedContent
this.editingCell.alternativeSelectedContent = this.editingCell.alternativeContentOptions[0] || null;
} else {
this.editingCell.alternativeSelectedContent = altKpiNumbers[0] || null;
}
Con estos cambios, cuando activas la multiselección, selectedContent contendrá un objeto con label y value correspondiente al primer KPI seleccionado, manteniendo el mismo formato que contentOptions.
Asegúrate de probar estos cambios para verificar que el comportamiento es el esperado y que no afecta otras partes de tu aplicación.
Resumen de los cambios:
Modificar toggleMultiSelection para asignar col.selectedContent como col.contentOptions[0].
Modificar applyKPI en multiselección para asignar this.editingCell.selectedContent como this.editingCell.contentOptions[0].
Si aplicable, modificar el manejo de alternativeSelectedContent en applyKPI.
Estos cambios garantizan que selectedContent será un objeto con label y value, igual que contentOptions, cuando la multiselección esté activada.