Как обновить sh встроенный редактор данных после получения данных из сервиса? - PullRequest
4 голосов
/ 05 марта 2020

Я добавил встроенные функции редактирования данных для моей таблицы данных. Я использую сервисный вызов для получения последних данных и привязываюсь к данным с помощью dtOptions. Я использую датируемый "". изначально пустая привязка переменных данных. как только я получаю данные из сервиса, я связываюсь с dtOptions, который хорошо связывает (показывает). но встроенное редактирование не работает. Я не уверен, как добавить данные в редактор после получения от службы. если я добавлю доступ к экземпляру $ .fn.dataTable.Editor. это просто не работает. Пожалуйста, помогите решить эту проблему.

HTML

<table id='dtGrid' *ngIf="dtRendered" datatable [dtOptions]="dtOptions" class="row-border hover"></table>

script

 data = [];

renderDatatable(dtColumns, modelObjAttributes) {
    console.log('dtEditor', this.dtEditor);
    const colLenth = dtColumns.length;
    this.dtRendered = false;
    this.dtOptions = {
        dom: 'Bfrtip',      
        data: this.data,
        pageLength: 100,
        columns: dtColumns,
        columnDefs: [ {
          targets: colLenth,
          defaultContent: '',
          title: '<i class="fa fa-plus plusIcon"></i>',
          orderable: false
        }],
        paging: true,
        searching: true,
      //  ordering: true,
        info:     false,
        responsive: true,
        drawCallback: () => {
          const btnElement = this.dtTableId.nativeElement.querySelector('i.plusIcon');
          this.renderer.listen(btnElement, 'click', ($event) => {
              this.onClickPlusIcon(modelObjAttributes);
           });
        },
        scrollY: '500px',
      //  bSort: false,
        scrollCollapse: true,
        select: {
          style:    'os',
          selector: 'td:first-child'
         },
        buttons: [
          { extend: 'create', editor: this.dtEditor },
          { extend: 'edit',   editor: this.dtEditor },
          { extend: 'remove', editor: this.dtEditor }
          // { extend:  'pageLength', editor: this.dtEditor}
        ]
      };
    this.cdr.detectChanges();
    this.dtRendered = true;
    this.cdr.detectChanges();
    this.attachPlusIconClickEvent(modelObjAttributes);
    this.attachDtClickEvent();
}

// This method used to initialize the data table dyanamically
initializeDtEditor(dtColumns, modelObjAttributes) {
    this.dtEditor = new $.fn.dataTable.Editor({  
    data: this.data,
    table: '#dtGrid',
    idSrc: this.uniqueField,
    fields: this.dataTableFields,
    formOptions: {
      inline: {
        onBackground:  'blur',
        onBlur:        'close',
        onComplete:    'close',
        onEsc:         'close',
        onFieldError:  'focus',
        onReturn:      'submit',
        submit:        'changed',
        scope:         'row'
      }
    }
   });
   // this.cdr.detectChanges();
    this.renderDatatable(dtColumns, modelObjAttributes);
}


// This method to get the data from service if you see i'm binding the reponseData to dtOptions. It adding to the datatable but it's not allowing to edit(inline edit). with buttong edit it's working.

getData(modelName) {
  this.dtServiceService.readData(modelName).subscribe(responseData => {
   // console.log(JSON.stringify(data));   
   this.dtOptions['data'] = responseData;
   this.dtRendered = false;
   this.cdr.detectChanges();
   this.dtRendered = true;
   this.cdr.detectChanges();

  },
  error => {
    console.log('data is not getting!');
  });
}

1 Ответ

2 голосов
/ 13 марта 2020

Angular -datatables предоставляет dtTrigger , который можно использовать для ручного запуска рендеринга таблицы.

Вам нужно вызвать dtTrigger для ручной визуализации таблицы.

Пример:

HTML:

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
  <tr>
    <th>ID</th>
    <th>First name</th>
    <th>Last name</th>
  </tr>
</thead>
<tbody>
  <tr *ngFor="let person of persons">
    <td>{{ person.id }}</td>
    <td>{{ person.firstName }}</td>
    <td>{{ person.lastName }}</td>
  </tr>
</tbody>
</table>

Машинопись:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject } from 'rxjs';
import { Person } from '../person';

import 'rxjs/add/operator/map';

@Component({
  selector: 'app-angular-way',
  templateUrl: 'angular-way.component.html'
})
export class AngularWayComponent implements OnDestroy, OnInit {
  dtOptions: DataTables.Settings = {};
  persons: Person[] = [];
  // We use this trigger because fetching the list of persons can be quite long,
  // thus we ensure the data is fetched before rendering
  dtTrigger: Subject = new Subject();

  constructor(private http: Http) { }

  ngOnInit(): void {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };
    this.http.get('data/data.json')
      .map(this.extractData)
      .subscribe(persons => {
        this.persons = persons;
        // Calling the DT trigger to manually render the table
        this.dtTrigger.next();
      });
  }

  ngOnDestroy(): void {
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();
  }

  private extractData(res: Response) {
    const body = res.json();
    return body.data || {};
  }
}
...