本文介绍了Angular Material mat-table 在组件中定义可重用列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道是否可以创建一个用于 mat-table 的列"组件,我曾尝试为常用的列定义创建一个组件,但是当添加到表格时,我收到一个无法找到的错误列选择器,我的列定义如下:

Anybody know if it is possible to create a "column" component for use with mat-table, I have tried creating a component for a commonly used column definition but when adding to the table i get an error that was unable to find the column selector, my column definition is below:

@Component({
  selector: 'iam-select-column',
  template: `
  <ng-container matColumnDef="select">
    <mat-header-cell *matHeaderCellDef>
      <mat-checkbox></mat-checkbox>
    </mat-header-cell>
    <mat-cell *matCellDef="let row">
      <mat-checkbox></mat-checkbox>
    </mat-cell>
  </ng-container>
  `,
  styles: [`
  `]
})
export class SelectColumnComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

并在表格中使用它

<mat-table class="mat-elevation-z8">

  <iam-select-column></iam-select-column>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>

</mat-table>

和显示的列是:

  displayedColumns = [
    'select'
  ];

是否可以这样做,因为我想避免在有选择列的表中重复?

Is it possible to do this as I would like to avoid the duplication in tables where I have a select column?

推荐答案

为了使其工作,您必须使用 table.addColumnDef 手动将 columnDef 添加到表格中> 方法.

In order to make it work you have to add that columnDef manually to table by using table.addColumnDef method.

@Component({
  selector: 'iam-select-column',
  template: `
    <ng-container matColumnDef="select">
        ...
    </ng-container>
  `
})
export class SelectColumnComponent implements OnInit {
  @ViewChild(MatColumnDef) columnDef: MatColumnDef;

  constructor(@Optional() public table: MatTable<any>, private cdRef: ChangeDetectorRef) { }

  ngOnInit() {
    if (this.table) {
      this.cdRef.detectChanges();
      this.table.addColumnDef(this.columnDef);
    }
  }
}

但在此之前,我们必须确保 matColumnDef 指令已经完成绑定初始化,以便它具有 name.为此,我们必须在该组件上运行 detectChanges.

But before doing this we have to make sure that matColumnDef directive has already finished bindings initialization so that it has name. For that we have to run detectChanges on that component.

Ng-run 示例

另一种方法是在父组件中提供该名称,如角度材料问题中所述https://github.com/angular/material2/issues/13808#issuecomment-434417804:

Another way is to provide that name in parent component as it described in angular material issuehttps://github.com/angular/material2/issues/13808#issuecomment-434417804:

parent.html

<mat-table class="mat-elevation-z8">

  <iam-select-column name="select"></iam-select-column>

选择列组件

@Input()
get name(): string { return this._name; }
set name(name: string) {
    this._name = name;
    this.columnDef.name = name;
}

这篇关于Angular Material mat-table 在组件中定义可重用列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:49