1

estoy trabajando con angular, estoy buscando una manera de agregar columnas a un ngx-datatable "dinámicamente" pero no puedo encontrar una manera. Lo que estoy tratando de lograr es apartir de algunos datos que me llegan del backend, crear checkbox y poder llenar la tabla con los datos que le corresponden.

el array que me llega del backend tiene este formato.

     row = [
      {role: "administrador", id: 1}
      {role: "operario", id: 2}
      {role: "visitante", id: 3}
     ]

lo que logre fue lo siguiente

introducir la descripción de la imagen aquí

Mi archivo grid.html

    <form appParentFormSubmit appChildFormSubmit [formGroup]="formGroup" 
    *ngIf="formField.name">

    <ngx-datatable #myTable class="material" style="width: 100%" [rows]="rows" 
    [columnMode]="ColumnMode.force"
    [headerHeight]="50" [footerHeight]="50" [rowHeight]="50" [limit]="5" 
    [selected]="selected"
    [selectionType]="SelectionType.checkbox" [selectAllRowsOnPage]="false" 
    [displayCheck]="displayCheck"
    (activate)="onActivate($event)" (select)="onSelect($event)" [scrollbarV]="false" 
    (page)="onPage($event)"
   [loadingIndicator]="loadingIndicator" [reorderable]="reorderable">

   <ngx-datatable-column [width]="60" [sortable]="false" [canAutoResize]="false" 
   [draggable]="false"
   [resizeable]="false" [headerCheckboxable]="true" [checkboxable]="true">
   </ngx-datatable-column>

   <ngx-datatable-column *ngFor="let col of columns; let i = index" [name]="col.name" 
   [flexGrow]="col.flexGrow">
   <ng-template ngx-datatable-header-template>
   {{ col.name }}
   </ng-template>
   <ng-template let-value="value" ngx-datatable-cell-template>
   {{ col.prop }}
   </ng-template>
   </ngx-datatable-column>

   <ngx-datatable-column [width]="80" [resizeable]="true" [sortable]="true" 
   [draggable]="true" [canAutoResize]="false"
   [frozenLeft]="false" [checkboxable]="true" [headerCheckboxable]="true" >

   </ngx-datatable-column>

  <ngx-datatable-column [width]="20" [resizeable]="true" [sortable]="true" 
  [draggable]="true" [canAutoResize]="false"
   [frozenLeft]="false">
   <ng-template let-row="row" let-expanded="expanded" ngx-datatable-cell-template>
     <a href="javascript:void(0)" [class.datatable-icon-right]="!expanded" 
    [class.datatable-icon-down]="expanded"
       title="Expand/Collapse Row" (click)="toggleExpandRow(row)">
     </a>
    </ng-template>
   </ngx-datatable-column>
 
   </ngx-datatable>
  </form>

Mi archivo generico grid.ts

      import { Component, OnInit, Input, ApplicationRef, ComponentFactoryResolver, 
      Injector, ViewChild, ElementRef } from '@angular/core';
      import { FormGroup } from '@angular/forms';
      import { ColumnMode,SelectionType } from '@swimlane/ngx-datatable';
      import { FormField } from '../../generic-input/models/form-field.model';

      @Component({
      selector: 'app-grid-row-detail',
      templateUrl: './grid-row-detail.component.html',
      })
      export class GridRowDetail<T> implements OnInit {
      @Input()
      formField: FormField<T> = new FormField();
      @Input()
      formGroup: FormGroup = new FormGroup({});
      @Input()
      required = false;
      @Input()
      classes: string;

      @ViewChild("myTable", { static: false }) table: any;
      public rows = [];

      public timeout: any;

      public selected = [];

      public columns = [];

      public ColumnMode = ColumnMode;

      public SelectionType = SelectionType;
  
      public resultColumns: any[] = [];

      public type = SelectionType;
      constructor() {
      }

      ngOnInit() {
      this.generateColumns();
      this.rows = this.formField.componentGridExpandable.row;
      this.columns = this.formField.componentGridExpandable.columns;

       }

       onSelect({ selected }) {
       console.log('Select Event', selected, this.selected);
       this.selected.splice(0, this.selected.length);
       this.selected.push(...selected);
       }

       onActivate(event) {
       console.log('Evento activado', event);
        }


        generateColumns() {
        this.formField.componentGridExpandable.row.forEach((item) => {

          this.formField.componentGridExpandable.columns.push({
           prop: item.role,
          })
          })
          console.log(this.formField.componentGridExpandable.columns);
   
         }
        }

El archivo en el cual armo la grilla add.grid.ts

          @Component({
          selector: 'app-add-update',
          templateUrl: './add-update.component.html',
            })
           export class AddUpdateComponent extends DefaultAddUpdateComponent<User> 
         implements OnInit 
          {
          public columns;
          public row;
          public id;

          formFields: FormField<User & { 'new-password'?: string, 'other-password'?: 
           string }>[] 
         = [
           {
           name: 'rols',
          label: 'roles',
           placeholder: 'search_by_id_number',
          type: 'componentGridExpandable',
          componentGridExpandable: {
          row:[

           ],
           columns: [
           {
           name: "Roles",
            prop: "role",
          },
          {
           name: "ID",
           prop: "id",
          }
          ],
           }
           },
            ];


          @ViewChild('genericForm', { read: false, static: false }) genericForm: 
          GenericFormComponent<User>;

           constructor(
           public activatedRoute: ActivatedRoute,
            public router: Router,
          public gridDataService: GridEventsService,
          public alertService: AlertService,
         public modalOutletService: ModalOutletService,
         private userService: UserService,
         private extrasService: ExtrasService,
         ) {
        super(activatedRoute, router, gridDataService, alertService, 
         modalOutletService);
        this.initVars();
          }

         ngOnInit() {
        super.ngOnInit();
         }

        async initVars() {
         const rolsType = (await this.extrasService.getRoles());
         const formFieldsData = this.formFields
        const datosversianda = [];
        const pushear = [];
       formFieldsData.map(function (dataCol) {
       if (dataCol.type === 'componentGridExpandable') {
       rolsType.map(item2 => {
      pushear.push({ role: item2.role, id: item2.id, permissions: item2.permissions 
      })
      })
     dataCol.componentGridExpandable.row = pushear
    }
    })
    }

    }

Cualquier ayuda se los agradezco, desde ya muchas gracias.

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.