Paginator не работает, когда я получаю данные из API в таблицу mat.Таблица матов генерируется динамически - PullRequest
0 голосов
/ 20 сентября 2019

Я создаю свою таблицу соответствия динамически, где столбцы проходят через массив, и данные также отображаются динамически.Mat-paginator отлично работал с локальным массивом.Но когда я получаю данные из API, он не отвечает.Я пробовал разные вещи, но не нашел решения.

Вот мой код из файла Html.

`

<div class="container">
  <div class="tableSearchRow">

    <div id="searchTitle">
      <button (click)="toggle()" [hidden]="show" class="searchButton">{{name}}<i class="material-icons searchIconImg"> search </i></button>
      <mat-form-field *ngIf="!isPrepositionChecked" >
        <input id="textupercase" matInput (keyup)="applyFilter($event.target.value)" placeholder="Search">
      </mat-form-field>
    </div>

    <div id="searchIcon"> 
        <button mat-raised-button (click)="openDialog()">+Add</button>
      </div>
  </div>

  <div  class="row">
    <mat-table #table [dataSource]="dataSource" >
      <ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
        <mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell>
        <mat-cell *matCellDef="let commonCode">{{column.cell(commonCode)}}</mat-cell>
      </ng-container>
      <ng-container cdkColumnDef="Actions">
        <mat-header-cell *cdkHeaderCellDef> Actions </mat-header-cell>
        <mat-cell *matCellDef="let commonCode; let i = index">
          <button mat-button (click)="updateDataDialog(i,commonCode)"><i class="material-icons blue">border_color</i></button>enter code here
          <button mat-button (click)="delete(commonCode.Code)"><i class="material-icons red">delete</i></button>
          <button mat-button routerLink="commonCodeValues"><i class="material-icons" >blur_circular</i></button>
          </mat-cell>
      </ng-container>

      <mat-header-row *matHeaderRowDef="displayedColumns" ></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;" ></mat-row>
    </mat-table>
      <mat-paginator  [pageSizeOptions]="[5,10, 20]"></mat-paginator>
  </div>
</div>

`

Код файла Js `

let  fields: any[] = [
  {
    type: 'text',
    name: 'Code',
    label: 'Code',
    value: '',
    required: true,
  },
  {
    type: 'text',
    name: 'Name',
    label: 'Name',
    value: '',
    required: true,
  },
  {
    type: 'text',
    name: 'Description',
    label: 'Description',
    value: '',
    required: true,
  },

];

@Component({
  selector: 'app-common-codes',
  templateUrl: './common-codes.component.html',
  styleUrls: ['../setupStyle.css']
})

export class CommonCodesComponent implements OnInit {

  @ViewChild(MatPaginator) paginator: MatPaginator; 
  dataSource: any;
  name="commonCode";


  Employee: any = [];

  // Columns Of Table
  columns = [
    { columnDef: 'Code', header: 'Code',    cell: (element: any) => `${element.Code}`},
    { columnDef: 'Name',     header: 'Name',   cell: (element: any) => `${element.Name}`},
    { columnDef: 'Description',   header: 'Description', cell: (element: any) => `${element.Description}`},
  ];

  displayedColumns = this.columns.map(c => c.columnDef).concat(['Actions']);

constructor(private dialog: MatDialog, private fb: FormBuilder, private setupService: SetupService) { 
  this.dataSource = new MatTableDataSource(this.json.transfer)
  // this.refresh()
   }

   ngOnInit() {
  // console.log(this.displayData());
  }

  ngAfterViewInit() {
    this.refresh();
    this.dataSource.paginator = this.paginator;
  }

  // Filter For Table
   applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  // Function to refresh data inside table
  refresh(){
    this.dataSource = new MatTableDataSource(JSON.parse(localStorage.getItem(this.name )));
  }

  // Function for search bar
  toggle(){
    this.show=true;
    this.isPrepositionChecked=false;
  }

  // Function For Adding New Table
  openDialog(){
    let regiForm  = this.fb.group({  
      'Code' : ['', Validators.required],  
      'Name' : ['', Validators.required],  
      'Description' : ['', Validators.required],  
    });
    this.setupService.openDialog(regiForm, fields, this.name).afterClosed().subscribe(res => {
      this.refresh()
    })
  }

  // Function for update Data inside table
  updateDataDialog(index, obj){
    let regiForm  = this.fb.group({  
            'Code' : [obj.Code, Validators.required],  
            'Name' : [obj.Name, Validators.required],  
            'Description' : [obj.Description, Validators.required],  
          });
    this.setupService.updateDialog(regiForm, fields, this.name, index ).afterClosed().subscribe(res => {
      this.refresh();
    })
  }

  // Function to remove data from table
  delete(id){
    this.setupService.deleteData().afterClosed().subscribe(res => {
      if(res){
        let items = JSON.parse(localStorage.getItem(this.name));
        for (var i =0; i<=items.length; i++) {
          if (items[i].Code == id) {
              console.log("id FOUND")
              items.splice(i,1)
              break;
          }
          else {
            console.log("id doesn't match")
          }
        }
        items = JSON.stringify(items);
        localStorage.setItem(this.name, items);
        this.refresh();
      }
    })
  }

  // displayData(){
  //   this.setupService.getData().subscribe((res : {}) => {
  //     this.Employee = res;
  //   });
  // }
}

`

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...