создать общую таблицу данных с использованием углового материала

Я хочу создать многоразовую таблицу данных углового материала, которая может использоваться любым компонентом, и мне нужно передавать только требуемый заголовок столбца и другие данные таблицы. Вот что я пробовал:

Я следую этому примеру: stackblitz

Создана shared папка в src/app папке. а также компонент таблицы данных, который можно будет использовать повторно.

data-table.component.html:

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
    <ng-container [matColumnDef]="tableData" *ngFor="let tableData of objectKeys(columnHeader)">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> {{columnHeader[tableData]}} </th>
        <td mat-cell *matCellDef="let element; let i=index;"> {{element[tableData]}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="objectKeys(columnHeader)"></tr>
    <tr mat-row *matRowDef="let row; columns: objectKeys(columnHeader);"></tr>
</table>

data-table.component.ts:

import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { MatSort, MatTableDataSource, MatPaginator } from '@angular/material';

@Component({
  selector: 'app-data-table',
  templateUrl: './data-table.component.html',
  styleUrls: ['./data-table.component.scss']
})
export class DataTableComponent implements OnInit {

  @Input() tableData;
  @Input() columnHeader;
  @Input() source;
  objectKeys = Object.keys;
  dataSource;

  @ViewChild(MatSort, { static: false }) sort: MatSort;
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;

  constructor() { }

  ngOnInit() {
    console.log(this.tableData);
    this.dataSource = new MatTableDataSource(this.tableData);
    this.dataSource.sort = this.sort;
  }

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

Теперь я использую селектор app-data-table там, где хочу. У меня есть компонент профиля, в котором я хочу его использовать.

profile-setup.component.html:

<app-data-table [tableData]="tableData" [columnHeader]="columnHeader"></app-data-table>

profile-setup.component.ts:

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { ProfileSetUp } from 'src/app/_interface/profile-setup.module';

@Component({
  selector: 'app-profile-setup',
  templateUrl: './profile-setup.component.html',
  styleUrls: ['./profile-setup.component.scss']
})


export class ProfileSetupComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  columnHeader = {'profileName': 'Profile Name', 'profileDesc': 'Description', 'adminUser': 'Admin User', 'id': ''};

  tableData: ProfileSetUp[] = [
    {
      id: 1,
      profileName: "Cameron Villams",
      profileDesc: "Face to face contact",
      adminUser: "Iwan Rynders",
      action: ""
    },
    {
      id: 2,
      profileName: "Charl Angle",
      profileDesc: "Face to face contact",
      adminUser: "Unknown",
      action: ""
    },
    {
      id: 3,
      profileName: "Johan Abraham",
      profileDesc: "Face to face contact",
      adminUser: "Unknown",
      action: ""
    },
    {
      id: 4,
      profileName: "Niekie Gadgilly",
      profileDesc: "Face to face contact",
      adminUser: "Unknown",
      action: ""
    },
    {
      id: 5,
      profileName: "Veer S",
      profileDesc: "Face to face contact",
      adminUser: "Unknown",
      action: ""
    }
  ];    
}

profile-setup.module:

export interface ProfileSetUp {
    id: number;
    profileName: string;
    profileDesc: string;
    adminUser: string;
    action: string;
}

Как я могу показать данные условно, например, некоторые таблицы данных могут иметь кнопки «Изменить», «Удалить», а некоторые из них не имеют этих кнопок. Любая помощь будет оценена по достоинству.


person Pathik Vejani    schedule 19.11.2019    source источник


Ответы (1)


можно передать функцию обратного вызова компоненту таблицы. (обновленный проект: stackblitz)

DataTableComponent

добавить вход для кнопки и вызов для нее.

  @Input() editButton;

  onEdit(element) {
    this.editButton(element);
  }

data-table.component.html

добавить логику, чтобы добавить кнопку для редактирования подключения обратного вызова.

<div *ngIf="columnHeader[tableData] != 'Edit'">
      <td mat-cell *matCellDef="let element"> {{element[tableData] }}</td>
</div>
<div *ngIf="columnHeader[tableData] == 'Edit'">
  <td mat-cell *matCellDef="let element"> 
      <button mat-button (click)="onEdit(element)">
        edit
      </button> 
  </td>
</div>

EmployeeComponent

добавить столбец редактирования.

columnHeader = {'studentID': 'ID', 'fname': 'First Name', 'lname': 'Last Name', 'weight': 'Weight', 'symbol': 'Code', 'edit': 'Edit'};

создать метод обратного вызова.

  onEditClick = (element) => this.onEdit(element);

  onEdit(element) {
    console.log(element);
  }

employee.component.html

<app-data-table [tableData]="tableData" [columnHeader]="columnHeader" [editButton]="onEditClick"></app-data-table>
person Rodrigo Luiz Zini Matias    schedule 21.08.2020