Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Tengo un componente angular que es un grid designer. En cada celda del grid cargo otros…

  1. User

    Tengo un componente angular que es un grid designer. En cada celda del grid cargo otros componentes a elección. Además tengo una opción de Activar multiselección, la cual permite elegir más de un componente a cargar en la celda para que mediante un el usuario pueda cambiar entre los componentes fuera del modo diseño perviamente elegidos. El problema es que da igual el orden en el que elija los componentes en el modo multiselección dado que luego los pone en el listado en un orden distinto y se muestra por defecto el primero de la lista. Necesito que me des el código para que cuando se elijan varios componentes en la multiselección, el orden de aparición fuera del modo diseño sea el orden en el que el usuario los ha elegido. Dame el código específico para cambiarlo indicándome el código anterior y el código nuevo en caso de reemplazar e indicándome donde tengo que ponerlo en caso de código nuevo.

    <div id="editor" class="editor-size"></div>
    <button class="button-apply-json" (click)="validateAndApplyJson()">
      Aceptar
    </button>
    
        <div *ngIf="col === editingCell" class="edit-container">
          <div class="cell-options-container">
            <label>
              <input type="checkbox" [(ngModel)]="col.showMultiSelection" (click)="toggleMultiSelection(col)">
              Activar multiselección
            </label>
          </div>
    
          <div class="cell-options-container">
            <label>
              <input type="checkbox" [(ngModel)]="col.showSwitch" (change)="toggleSwitch(col)">
              Activar switch
            </label>
          </div>
    
          <!-- listbox del primer kpi -->
          <ng-select appendTo="body" class="kpi-select-designer1" [searchable]="true" [(ngModel)]="col.content"
            *ngIf="col === editingCell" [items]="componentOptions" bindLabel="label" bindValue="value"
            [multiple]="col.multiSelection" placeholder="Elige uno o más KPIs">
          </ng-select>
    
          <!-- listbox del kpi alternativo -->
          <ng-select *ngIf="col.showSwitch" class="kpi-select" [searchable]="true" [(ngModel)]="col.alternativeContent"
            [items]="componentOptions" bindLabel="label" bindValue="value"
            placeholder="Componente alternativo"></ng-select>
    
          <div class="button-container">
            <button class="button-add" *ngIf="col.showMultiSelection" class="button-add">
              +
            </button>
            <button class="button-apply" (click)="applyKPI()">
              Aplicar
            </button>
          </div>
        </div>
        <ng-container *ngIf="!col.isComponent">{{ col.content }}</ng-container>
        <ng-container *ngIf="col.isComponent">
          <div class="cell-content">
            <!-- ng-select for single selection in non-multiselection mode -->
            <div *ngIf="col.multiSelection === false" class="cell-options-container">
              <!-- listbox de la selección simple -->
              <ng-select *ngIf="!col.isCard" class="kpi-select-disabled" id="kpi-select-viewer"
                [(ngModel)]="col.selectedContent" [items]="col.contentOptions" [disabled]="true" [multiple]="false"
                [clearable]="false" [searchable]="false" (change)="onMultiselectionListChange($event, col)">
                <ng-template ng-label-tmp let-item="item">
                  {{ getLabelTitle(item.label) }}
                </ng-template>
              </ng-select>
            </div>
            <div *ngIf="col.showSwitch || col.showMultiSelection" class="cell-options-container">
    
              <!-- listbox de la multiselección -->
              <ng-select *ngIf="col.multiSelection" class="kpi-select-multi" id="kpi-select-viewer"
                [(ngModel)]="col.selectedContent" [items]="col.contentOptions" [multiple]="false" [clearable]="false"
                [searchable]="false" (change)="onMultiselectionListChange($event, col)">
                <ng-template ng-label-tmp let-item="item">
                  {{ getLabelTitle(item.label) }}
                </ng-template>
              </ng-select>
    
              <!-- switch central -->
              <div *ngIf="col.showSwitch" class="switch">
                <div class="left" [class.active]="col.switchActiveSide === 'left'"
                  (click)="switchComponent(col,'left')">
                  {{ col.switchLeftText }}
                </div>
                <div class="right" [class.active]="col.switchActiveSide === 'right'"
                  (click)="switchComponent(col,'right')">
                  {{ col.switchRightText }}
                </div>
              </div>
              <!-- parte de botones -->
              <span class="right-title">Botones</span>
            </div>
            <div class="component-container">
              <ng-container #dynamicComponentContainer>
                <ngx-spinner [name]="'spinner-' + rowIndex + '-' + colIndex" bdColor="rgba(51,51,51,0.3)" size="medium"
                  color="#fff" type="ball-scale-multiple" [fullScreen]="false">
                </ngx-spinner>
              </ng-container>
            </div>
          </div>
        </ng-container>
      </div>
    </div>
    

    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';

    @Component({ selector: 'app-grid-designer', standalone: true, imports: [CommonModule, FormsModule, NgSelectModule, NgxSpinnerModule], templateUrl: './grid-designer.component.html', styleUrl: './grid-designer.component.scss', }) export class GridDesignerComponent implements OnInit, AfterViewInit { @ViewChildren('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainers!: QueryList; @ViewChild('contextMenu') contextMenuElement!: ElementRef; private kpiService = inject(KpiService);

    gridData: any[] = []; gridDataString: string = ''; isHidden = false; jsonValid: boolean | null = null; private editor: ace.Ace.Editor | null = null; editingCell: any = null; contextMenuVisible = false; contextMenuX = 0; contextMenuY = 0; selectedCell: any = null; componentOptions: { label: string; value: any }[] = [];

    constructor(private http: HttpClient, private toastr: ToastrService, private spinner: NgxSpinnerService ) { }

    ngOnInit(): void { this.getListKPI() this.http.get('assets/grid-default.json').subscribe((data: any) => { this.gridData = this.initializeGridData(data); this.gridDataString = JSON.stringify(this.gridData, null, 2); this.updateEditorValue(); this.configToastr(); }); }

    ngAfterViewInit(): void { this.initAceEditor(); setTimeout(() => this.renderDynamicComponents(), 100); }

    getListKPI(): void { this.kpiService.getListKPI().subscribe( (data: any[]) => { this.componentOptions = data.map(item => ({ label: kpi-${item.idKPI} - ${item.representacion} - ${item.nombre}, value: item.idKPI })); }, (error: any) => { // Manejo de errores } ); }

    getLabelTitle(label: string): string { const parts = label.split(' - '); return parts[parts.length - 1]; }

    onMultiselectionListChange(e: any, col: any) { console.log("🔰 ~ onMultiselectionListChange ~ col:", col) console.log("🔰 ~ onMultiselectionListChange ~ e:", e) const { rowIndex, colIndex } = this.getCellIndices(col); this.renderDynamicComponents(rowIndex, colIndex); }

    getCellIndices(cell: any): { rowIndex: number, colIndex: number } { for (let i = 0; i < this.gridData.length; i++) { const row = this.gridData[i]; const columns = row.columns; for (let j = 0; j < columns.length; j++) { if (columns[j] === cell) { return { rowIndex: i, colIndex: j }; } } }

    return { rowIndex: -1, colIndex: -1 }; // Si no se encuentra
    

    }

    private initializeGridData(data: any[]): any[] { return data.map(row => ({ ...row, columns: row.columns.map((col: any) => ({ ...col, content: col.content || null, alternativeContent: null, showSwitch: false, switchLeftText: 'Izquierda', // texto por defecto switchRightText: 'Derecha', // texto por edfecto switchActiveSide: 'left', // switch izquierdo por defecto multiSelection: false })), height: row.height || '20%', })); }

    private initAceEditor(): void { const editorElement = document.getElementById('editor'); if (editorElement) { this.editor = ace.edit(editorElement); this.editor.setTheme('ace/theme/dracula'); this.editor.session.setMode('ace/mode/json'); this.editor.setOptions({ fontSize: '14px', showPrintMargin: false, showGutter: true, highlightActiveLine: true, enableBasicAutocompletion: true, enableLiveAutocompletion: true, enableSnippets: true, });

      this.updateEditorValue();
    
      this.editor.getSession().on('change', () => {
        this.gridDataString = this.editor?.getValue() ?? '';
        this.jsonValid = false;
      });
    } else {
      console.error('Error al inicializar el Editor Ace');
    }
    

    }

    onRightClick(event: MouseEvent, cell: any) { event.preventDefault(); this.contextMenuVisible = true; this.contextMenuX = event.clientX; this.contextMenuY = event.clientY; this.selectedCell = cell; }

    @HostListener('document:click') onDocumentClick() { this.contextMenuVisible = false; }

    addColumnToRow() { if (this.selectedCell) { const rowIndex = this.gridData.findIndex((row) => row.columns.includes(this.selectedCell) ); if (rowIndex !== -1) { const newColumn = { width: 'auto', content: '', colSpan: 1, rowSpan: 1, isComponent: false, multiSelection: false, }; this.gridData[rowIndex].columns.push(newColumn); this.updateJsonAndEditor(); } } this.contextMenuVisible = false; }

    changeRowHeight(event: Event, row: any) { const inputElement = event.target as HTMLInputElement; row.height = this.validateHeight(inputElement.value); this.updateJsonAndEditor(); }

    private validateHeight(value: string): string { if (value.endsWith('px') || value.endsWith('%')) { return value; } const num = parseInt(value); if (isNaN(num)) return '20%'; return ${Math.max(5, Math.min(100, num))}%; }

    changeWidth(event: Event) { if (this.selectedCell) { const inputElement = event.target as HTMLInputElement; this.selectedCell.width = this.validateWidth(inputElement.value); this.updateJsonAndEditor(); } }

    private validateWidth(value: string): string { if (value.endsWith('px') || value.endsWith('%')) { return value; } const num = parseInt(value); if (isNaN(num)) return '100%'; return ${Math.max(10, Math.min(100, num))}%; }

    adjustWidth(change: number) { if (this.selectedCell) { if (!this.selectedCell.width || this.selectedCell.width === 'auto') { this.selectedCell.width = '100%'; }

      if (this.selectedCell.width.endsWith('px')) {
        const currentPx = parseInt(this.selectedCell.width);
        this.selectedCell.width = `${Math.max(50, currentPx + change)}px`;
      } else {
        const currentPercent = parseInt(this.selectedCell.width);
        this.selectedCell.width = `${Math.max(
          10,
          Math.min(100, currentPercent + change)
        )}%`;
      }
      this.updateJsonAndEditor();
    }
    

    }

    adjustRow(row: any, change: number) { if (!row.height || row.height === 'auto') { row.height = '20%'; }

    if (row.height.endsWith('px')) {
      const currentPx = parseInt(row.height);
      row.height = `${Math.max(50, Math.min(900, currentPx + change))}px`;
    } else {
      const currentPercent = parseInt(row.height);
      row.height = `${Math.max(5, Math.min(100, currentPercent + change))}%`;
    }
    this.updateJsonAndEditor();
    

    }

    getSelectedRow(): any { return this.gridData.find((row) => row.columns.includes(this.selectedCell)); }

    adjustColSpan(change: number) { if (this.selectedCell) { this.selectedCell.colSpan = Math.max( 1, (this.selectedCell.colSpan || 1) + change ); this.updateJsonAndEditor(); } }

    adjustRowSpan(change: number) { if (this.selectedCell) { this.selectedCell.rowSpan = Math.max( 1, (this.selectedCell.rowSpan || 1) + change ); this.updateJsonAndEditor(); } }

    deleteCell() { if (this.selectedCell) { const rowIndex = this.gridData.findIndex((row) => row.columns.includes(this.selectedCell) ); if (rowIndex !== -1) { const columnIndex = this.gridData[rowIndex].columns.indexOf( this.selectedCell ); this.gridData[rowIndex].columns.splice(columnIndex, 1); if (this.gridData[rowIndex].columns.length === 0) { this.gridData.splice(rowIndex, 1); } this.updateJsonAndEditor(); } } this.contextMenuVisible = false; }

    addRow() { const newRow = { height: '100px', columns: [ { width: '100%', content: '', colSpan: 1, rowSpan: 1, isComponent: false, multiSelection: false, }, ], }; this.gridData.push(newRow); this.updateJsonAndEditor(); }

    addColumn() { this.gridData.forEach((row) => { row.columns.push({ content: '', colSpan: 1, rowSpan: 1, isComponent: false, }); }); this.updateJsonAndEditor(); }

    updateJsonAndEditor() { this.gridDataString = JSON.stringify(this.gridData, null, 2); this.updateEditorValue(); }

    private updateEditorValue(): void { if (this.editor && this.gridDataString) { this.editor.setValue(this.gridDataString); this.editor.clearSelection(); } }

    configToastr() { this.toastr.toastrConfig.positionClass = 'toast-top-full-width'; this.toastr.toastrConfig.extendedTimeOut = 0; this.toastr.toastrConfig.timeOut = 2900; }

    toggleSidebar() { this.isHidden = !this.isHidden; }

    getGridTemplateColumns(columns: any[]): string { return columns.map((col) => col.width).join(' '); }

    getGridTemplateRows(): string { return this.gridData.map((row) => row.height).join(' '); }

    validateAndApplyJson() { try { const parsedData = JSON.parse(this.gridDataString); this.gridData = parsedData; this.jsonValid = true; setTimeout(() => this.renderDynamicComponents(), 100); } catch (error) { this.jsonValid = false; this.toastr.warning(Error al procesar el JSON: ${error}, 'Advertencia'); } }

    renderDynamicComponents(specificRowIndex?: number, specificColIndex?: number): void { console.log("🔰 ~ renderDynamicComponents ~ specificRowIndex:", specificRowIndex, "specificColIndex:", specificColIndex); setTimeout(() => { if (!this.dynamicComponentContainers) return;

      let containerIndex = 0;
      this.gridData.forEach((row, rowIndex) => {
        row.columns.forEach((col: any, colIndex: number) => {
          if (col.isComponent) {
            if (specificRowIndex === undefined || (rowIndex === specificRowIndex && colIndex === specificColIndex)) {
              const container = this.dynamicComponentContainers.get(containerIndex);
              if (container) {
                container.clear();
                this.createComponent(container, col, rowIndex, colIndex);
              }
            }
            containerIndex++;
          }
        });
      });
    }, 100);
    

    }

    async createComponent(container: ViewContainerRef, col: any, rowIndex: number, colIndex: number): Promise { this.spinner.show(); try { const spinnerName = spinner-${rowIndex}-${colIndex}; this.spinner.show(spinnerName);

      let kpiNumber;
    
      if (col.showSwitch) {
        if (col.switchActiveSide === 'left') {
          kpiNumber = col.selectedContent.value;
        } else {
          kpiNumber = col.alternativeSelectedContent.value;
        }
      } else {
        kpiNumber = col.selectedContent.value;
      }
    
      const ComponentType = await this.loadDynamicComponent(`kpi-${kpiNumber}`);
      const componentRef = container.createComponent(ComponentType);
    
      (componentRef.instance as any).kpiNumber = kpiNumber;
    
      if ((componentRef.instance as any).isCard) {
        col.isCard = true;
      } else {
        col.isCard = false;
      }
    
      this.spinner.hide(spinnerName);
    
    } catch (error) {
      this.spinner.hide(`spinner-${rowIndex}-${colIndex}`);
      this.toastr.error(`Error al crear el componente:`);
    }
    

    }

    private async loadDynamicComponent(componentName: string): Promise { const kpiNumber = parseInt(componentName.split('-')[1]); const kpiRequest = { fechaDesde: "2023-01-01", fechaHasta: "2023-12-31", listKpi: [kpiNumber], sucursales: "" };

    const data = await this.kpiService.getKPI(kpiRequest).toPromise();
    console.log("🔰 ~ loadDynamicComponent ~ data:", data)
    
    let representacion: string | null = null;
    if (data.representacion) {
      representacion = data.representacion.toLowerCase();
    }
    
    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}`);
    }
    
    console.log("🔰 ~ loadDynamicComponent ~ representacion:", representacion)
    
    try {
      const module = await import(`../kpi-components/kpi-${representacion}/kpi-${representacion}.component`);
      const componentKey = Object.keys(module).find(key => key.toLowerCase() === `kpi${representacion}component`);
    
      if (!componentKey) {
        throw new Error(`No se encontró el componente para: ${representacion}`);
      }
    
      return module[componentKey];
    } catch (error) {
      console.error(`Error al cargar el componente: ${error}`);
      this.toastr.error(`No se pudo cargar el componente para: ${representacion}`);
      throw error;
    }
    

    }

    editKPI(col: any) { console.log("🔰 ~ editKPI ~ col:", col) if (Array.isArray(col.content)) { col.content = col.content.map((item: number) => kpi-${item}).join(', '); } else if (typeof col.content !== 'string' || !col.content.startsWith('kpi-')) { col.content = null; }

    col.switchLeftText = col.switchLeftText || 'Izquierda';
    col.switchRightText = col.switchRightText || 'Derecha';
    this.editingCell = col;
    

    }

    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.contentOptions[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) { // cambiar entre content y alternativecontent [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 indices de las celdas
    const { rowIndex, colIndex } = this.getCellIndices(col);
    
    // Renderizar el componente
    this.renderDynamicComponents(rowIndex, colIndex);
    
    // Actualizar Json y editor
    this.updateJsonAndEditor();
    

    }

    applyKPI() { if (this.editingCell.content) { let kpiNumbers = Array.isArray(this.editingCell.content) ? this.editingCell.content : [this.editingCell.content];

      kpiNumbers = kpiNumbers.map((item: any) => this.extractKpiNumber(item.toString()));
      this.editingCell.content = kpiNumbers;
    
      if (this.editingCell.multiSelection) {
        // Multiselección
        this.editingCell.contentOptions = this.componentOptions.filter(option => this.editingCell.content.includes(option.value));
        this.editingCell.selectedContent = this.editingCell.contentOptions[0] || null;
      } else {
        // Selección simple
        const kpiNumber = this.extractKpiNumber(this.editingCell.content.toString());
        this.editingCell.content = kpiNumber;
        this.editingCell.selectedContent = this.componentOptions.find(option => option.value === kpiNumber) || null;
      }
    }
    
    
    if (this.editingCell.showSwitch && this.editingCell.alternativeContent) {
      let altKpiNumbers = Array.isArray(this.editingCell.alternativeContent)
        ? this.editingCell.alternativeContent
        : [this.editingCell.alternativeContent];
    
    
      altKpiNumbers = altKpiNumbers.map((item: any) => this.extractKpiNumber(item.toString()));
      this.editingCell.alternativeContent = altKpiNumbers;
    
      if (this.editingCell.multiSelection) {
        this.editingCell.alternativeContentOptions = this.componentOptions.filter(option => this.editingCell.alternativeContent.includes(option.value));
        this.editingCell.alternativeSelectedContent = this.editingCell.alternativeContentOptions[0] || null;
      } else {
        const altKpiNumber = altKpiNumbers[0] || null;
        this.editingCell.alternativeSelectedContent = this.componentOptions.find(option => option.value === altKpiNumber) || null;
      }
    }
    
    this.editingCell.isComponent = true;
    
    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;
    

    }

    }

  2. Assistant

    Para lograr que el orden de aparición de los componentes fuera del modo diseño sea el mismo que el orden en el que el usuario los ha seleccionado, necesitas modificar la forma en que construyes col.contentOptions. Actualmente, al usar filter, estás obteniendo los componentes pero en el orden de componentOptions, no en el orden de selección del usuario.

    Debes reemplazar filter por map sobre col.content para obtener los componentes en el mismo orden en que fueron seleccionados.

    Cambios específicos en el código:

    1. En la función toggleMultiSelection(col: any):

    Código anterior:

    // 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.contentOptions[0] || null;
    

    Código nuevo:

    // Actualizamos contentOptions para que tenga solo las opciones seleccionadas en el orden de selección
    col.contentOptions = col.content.map((value: any) => 
      this.componentOptions.find(option => option.value === value)
    );
    
    // Ponemos el [0] de selectedContent como el primer KPI seleccionado por defecto
    col.selectedContent = col.contentOptions[0] || null;
    

    Explicación: Al utilizar col.content.map, recorres los valores seleccionados por el usuario y obtienes los objetos de componentOptions correspondientes, preservando el orden de selección.


    1. En la función applyKPI(), en la sección de multiselección:

    Código anterior:

    if (this.editingCell.multiSelection) {
      // Multiselección
      this.editingCell.contentOptions = this.componentOptions.filter(option => this.editingCell.content.includes(option.value));
      this.editingCell.selectedContent = this.editingCell.contentOptions[0] || null;
    } else {
      // Selección simple
      // ...
    }
    

    Código nuevo:

    if (this.editingCell.multiSelection) {
      // Multiselección
      this.editingCell.contentOptions = this.editingCell.content.map((value: any) => 
        this.componentOptions.find(option => option.value === value)
      );
      this.editingCell.selectedContent = this.editingCell.contentOptions[0] || null;
    } else {
      // Selección simple
      // ...
    }
    

    Explicación: Aquí también reemplazas el uso de filter por map para mantener el orden de selección del usuario en contentOptions.


    1. Si utilizas alternativeContent en multiselección, también debes aplicar el mismo cambio:

    Código anterior:

    if (this.editingCell.multiSelection) {
      this.editingCell.alternativeContentOptions = this.componentOptions.filter(option => this.editingCell.alternativeContent.includes(option.value));
      this.editingCell.alternativeSelectedContent = this.editingCell.alternativeContentOptions[0] || null;
    } else {
      // ...
    }
    

    Código nuevo:

    if (this.editingCell.multiSelection) {
      this.editingCell.alternativeContentOptions = this.editingCell.alternativeContent.map((value: any) => 
        this.componentOptions.find(option => option.value === value)
      );
      this.editingCell.alternativeSelectedContent = this.editingCell.alternativeContentOptions[0] || null;
    } else {
      // ...
    }
    

    Dónde realizar los cambios:

    • Reemplaza las secciones indicadas en las funciones toggleMultiSelection(col: any) y applyKPI() en tu componente TypeScript.

    Resultado esperado: Con estos cambios, el orden de los componentes seleccionados en el modo multiselección se mantendrá tal y como el usuario los eligió, asegurando que la experiencia del usuario sea coherente y predecible.


    Ejemplo del código modificado en contexto:

    // Dentro de toggleMultiSelection(col: any):
    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 en el orden de selección
      col.contentOptions = col.content.map((value: any) => 
        this.componentOptions.find(option => option.value === value)
      );
    
      // Ponemos el [0] de selectedContent como el primer KPI seleccionado por defecto
      col.selectedContent = col.contentOptions[0] || null;
    } else {
      // ...
    }
    
    // Dentro de applyKPI():
    if (this.editingCell.content) {
      let kpiNumbers = Array.isArray(this.editingCell.content)
        ? this.editingCell.content
        : [this.editingCell.content];
    
      kpiNumbers = kpiNumbers.map((item: any) => this.extractKpiNumber(item.toString()));
      this.editingCell.content = kpiNumbers;
    
      if (this.editingCell.multiSelection) {
        // Multiselección
        this.editingCell.contentOptions = this.editingCell.content.map((value: any) => 
          this.componentOptions.find(option => option.value === value)
        );
        this.editingCell.selectedContent = this.editingCell.contentOptions[0] || null;
      } else {
        // Selección simple
        // ...
      }
    }
    

    De esta forma, garantizas que el orden de contentOptions coincida con el orden en que el usuario seleccionó los componentes, solucionando el problema planteado.