Tengo un componente angular que es un grid designer donde puedo editar celdas y renderizar componentes en ellas.Tiene una opción de multiselección para elegir varios componentes y después en el modo visualización elegir entre ellos con un ng-select, pero al elegir entre varios tiene que renderizar el primero de la lista por defecto.
El problema es que para renderizar ese componente, en createComponent tengo kpiNumber = col.selectedContent.value; y necesito que sea así, pero en col.selectedContent se está metiendo solo un número sin array de label y value y necesito que se inserte también como array de label y value para que kpiNumber = col.selectedContent.value; funcione.
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;
}
}
The issue you're encountering arises because col.selectedContent is being set to a number (the kpiNumber), whereas in your createComponent method, you're expecting col.selectedContent to be an object with both label and value properties (i.e., { label: ..., value: ... }). This mismatch causes col.selectedContent.value to be undefined when col.selectedContent is just a number.
To resolve this problem, you need to ensure that col.selectedContent is always an object containing both label and value. You can achieve this by adjusting the code where col.selectedContent is set. Specifically, whenever you set col.selectedContent, you should set it to the corresponding object from your componentOptions, rather than just the kpiNumber.
Here's how you can modify your code to fix the issue:
In applyKPI():
Replace the line where col.selectedContent is set during multiselection. Change:
This ensures that col.selectedContent is an object from contentOptions.
Ensure Consistency When Switching Components:
In the switchComponent() method, if you're swapping selectedContent between content and alternativeContent, make sure to also swap the corresponding contentOptions and update selectedContent accordingly.
By making these changes, col.selectedContent will always be an object with label and value properties, ensuring that kpiNumber = col.selectedContent.value; works as expected in your createComponent method.
Here's the modified code sections for clarity:
In applyKPI():
if (this.editingCell.multiSelection) {
// Filter the selected options for contentOptions
this.editingCell.contentOptions = this.componentOptions.filter(option => this.editingCell.content.includes(option.value));
// Set selectedContent to the first option in contentOptions
this.editingCell.selectedContent = this.editingCell.contentOptions[0] || null;
} else {
// Single selection logic remains unchanged
this.editingCell.selectedContent = kpiNumbers[0] || null;
}
In toggleMultiSelection():
if (col.multiSelection) {
// Ensure col.content is an array
col.content = Array.isArray(col.content) ? col.content : [col.content];
// Update contentOptions with the selected options
col.contentOptions = this.componentOptions.filter(option => col.content.includes(option.value));
// Set selectedContent to the first option in contentOptions
col.selectedContent = col.contentOptions[0] || null;
} else {
// Logic for non-multiselection
// ...
}
In createComponent():
Your existing code will now work correctly:
if (col.multiSelection) {
// Now col.selectedContent is an object with label and value
kpiNumber = col.selectedContent.value;
} else {
// Existing logic
// ...
}
By ensuring col.selectedContent is always an object with label and value, your component creation logic can reliably access col.selectedContent.value without any issues.
Summary:
Update how col.selectedContent is set in your code to ensure it is an object { label, value }.
Set col.selectedContent to the first element of col.contentOptions, which contains the appropriate object.
This change allows kpiNumber = col.selectedContent.value; to work as intended in createComponent().
Note: After making these changes, test your application thoroughly to ensure that the changes work as expected in all scenarios, including when switching between multi-selection and single-selection modes, and when toggling components.