【问题标题】:Angular Material editable table using FormArray使用 FormArray 的 Angular Material 可编辑表
【发布时间】:2018-12-11 12:13:12
【问题描述】:

我正在尝试使用最新的材料+cdk 为角度构建一个内联可编辑表。

问题

如何使 mat-table 使用 [formGroupName] 以便表单字段可以通过其正确的表单路径引用?

这是我目前得到的:Complete StackBlitz example

模板

<form [formGroup]="form">
  <h1>Works</h1>
  <div formArrayName="dates" *ngFor="let date of rows.controls; let i = index;">
    <div [formGroupName]="i">
      <input type="date" formControlName="from" placeholder="From date">
      <input type="date" formControlName="to" placeholder="To date">
    </div>
  </div>


  <h1>Wont work</h1>
  <table mat-table [dataSource]="dataSource" formArrayName="dates">
    <!-- Row definitions -->
    <tr mat-header-row *matHeaderRowDef="displayColumns"></tr>
    <tr mat-row *matRowDef="let row; let i = index; columns: displayColumns;" [formGroupName]="i"></tr>

    <!-- Column definitions -->
    <ng-container matColumnDef="from">
      <th mat-header-cell *matHeaderCellDef> From </th>
      <td mat-cell *matCellDef="let row"> 
        <input type="date" formControlName="from" placeholder="From date">
      </td>
    </ng-container>

    <ng-container matColumnDef="to">
      <th mat-header-cell *matHeaderCellDef> To </th>
      <td mat-cell *matCellDef="let row">
        <input type="date" formControlName="to" placeholder="To date">
      </td>
    </ng-container>
  </table>
  <button type="button" (click)="addRow()">Add row</button>
</form>

组件

export class AppComponent implements  OnInit  {
  data: TableData[] = [ { from: new Date(), to: new Date() } ];
  dataSource = new BehaviorSubject<AbstractControl[]>([]);
  displayColumns = ['from', 'to'];
  rows: FormArray = this.fb.array([]);
  form: FormGroup = this.fb.group({ 'dates': this.rows });

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.data.forEach((d: TableData) => this.addRow(d, false));
    this.updateView();
  }

  emptyTable() {
    while (this.rows.length !== 0) {
      this.rows.removeAt(0);
    }
  }

  addRow(d?: TableData, noUpdate?: boolean) {
    const row = this.fb.group({
      'from'   : [d && d.from ? d.from : null, []],
      'to'     : [d && d.to   ? d.to   : null, []]
    });
    this.rows.push(row);
    if (!noUpdate) { this.updateView(); }
  }

  updateView() {
    this.dataSource.next(this.rows.controls);
  }
}

问题

这行不通。控制台产生

错误错误:找不到带有路径的控件:'dates -> from'

似乎[formGroupName]="i" 没有效果,因为使用formArray 时路径应该是dates -&gt; 0 -&gt; from

我目前的解决方法:对于这个问题,我已经绕过内部路径查找(formControlName="from")并直接使用表单控件:[formControl]="row.get('from')",但是我想知道我如何(或者至少为什么我不能)使用响应式表单的首选方式。

欢迎任何提示。谢谢。


因为我认为这是一个错误,所以我在 angular/material2 github 存储库中注册了 an issue

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    我会使用我们可以在matCellDef 绑定中获得的索引:

    *matCellDef="let row; let index = index" [formGroupName]="index"
    

    Forked Stackblitz

    要解决排序和过滤问题,请查看此答案Angular Material Table Sorting with reactive formarray

    【讨论】:

    • 不会从列而不是行生成索引吗?
    • 可以打印索引stackblitz.com/edit/…查看
    • 看起来工作正常。奇怪,如果这是故意的,那是不直观的。不过谢谢。
    • 这会在使用分页和过滤时产生问题,我现在正在努力解决这个问题......分页很容易解决,但不是过滤
    • @Pizzicato 使用索引作为 formGroupName 时如何解决分页问题。我也面临同样的问题。
    【解决方案2】:

    这里是示例代码

    在 HTML 中:

        <form [formGroup]="tableForm">
    
        <mat-table formArrayName="users" [dataSource]="dataSource">
    
          <ng-container cdkColumnDef="position">
            <mat-header-cell *cdkHeaderCellDef> No. </mat-header-cell>
            <mat-cell *cdkCellDef="let row let rowIndex = index"  [formGroupName]="rowIndex"> 
              <input type="text" size="2" formControlName="position"> </mat-cell>
          </ng-container>
    
    
          <ng-container cdkColumnDef="name">
            <mat-header-cell *cdkHeaderCellDef> Name </mat-header-cell>
            <mat-cell *cdkCellDef="let row let rowIndex = index"  [formGroupName]="rowIndex"> 
              <input type="text" size="7" formControlName="name">
            </mat-cell>
          </ng-container>
    
            <ng-container cdkColumnDef="weight">
            <mat-header-cell *cdkHeaderCellDef> Weight </mat-header-cell>
            <mat-cell *cdkCellDef="let row let rowIndex = index"  [formGroupName]="rowIndex"> 
              <input type="text" size="3" formControlName="weight">
            </mat-cell>
          </ng-container>
    
            <ng-container cdkColumnDef="symbol">
            <mat-header-cell *cdkHeaderCellDef> Symbol </mat-header-cell>
            <mat-cell *cdkCellDef="let row let rowIndex = index"  [formGroupName]="rowIndex"> 
              <input type="text" size="2" formControlName="symbol">
            </mat-cell>
          </ng-container>
    
          <!-- Header and Row Declarations -->
          <mat-header-row *cdkHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *cdkRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
        </form>
    

    控制器代码:

        displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
    
    
         dataSource ;
          tableForm: FormGroup;
    
    
    
         constructor(private formBuilder: FormBuilder){
         this.dataSource = [
          {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
          {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
          {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
          {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
          {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
          {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
          {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
          {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
          {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
          {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
        ];
          }
    
          ngOnInit(){
            this.tableForm= this.formBuilder.group({
                users: this.formBuilder.array([])
            })
            this.setUsersForm();
            this.tableForm.get('users').valueChanges.subscribe(users => {console.log('users', users)});
          }
          private setUsersForm(){
            const userCtrl = this.tableForm.get('users') as FormArray;
            this.dataSource.forEach((user)=>{
              userCtrl.push(this.setUsersFormArray(user))
            })
          };
          private setUsersFormArray(user){
    
    
            return this.formBuilder.group({
                position:[user.position],
                name:[user.name],
                weight:[user.weight], 
                symbol:[user.symbol]
            });
          }
    

    【讨论】:

    • 嗨,很好的答案,你能编辑你的答案以添加 mat-error 实现吗?
    • 本例中如何实现分页器?
    • For pagination :Pagination 要对表格的数据进行分页,在表格后面添加一个 。如果您使用 MatTableDataSource 作为表的数据源,只需将 MatPaginator 提供给您的数据源。它将自动侦听用户所做的页面更改并将正确的分页数据发送到表。查看此链接以获取更多信息material.angular.io/components/table/overview#datasource
    • 我得到:找不到名称为“0”的控件
    • 我错过了 formArrayName="users"。现在我得到:错误:找不到带有路径的控件:'users -> 0'
    【解决方案3】:

    聚会有点晚了,但我设法让它在不依赖索引的情况下工作。此解决方案还支持来自MatTableDataSource 的过滤等。

    https://stackblitz.com/edit/angular-material-table-with-form-59imvq

    组件

    import {
      Component, ElementRef, OnInit
    } from '@angular/core';
    import { Observable } from 'rxjs';
    import { map } from 'rxjs/operators'
    import { AlbumService } from './album.service';
    import { UserService } from './user.service';
    import { Album } from './album.model';
    import { User } from './user.model';
    import { FormArray, FormGroup, FormBuilder } from '@angular/forms';
    import { MatTableDataSource } from '@angular/material';
    
    @Component({
      selector: 'table-form-app',
      templateUrl: 'app.component.html'
    })
    export class AppComponent implements OnInit {
      form: FormGroup;
      users: User[] = [];
      dataSource: MatTableDataSource<any>;
      displayedColumns = ['id', 'userId', 'title']
      constructor(
        private _albumService: AlbumService,
        private _userService: UserService,
        private _formBuilder: FormBuilder
        ) {}
    
      ngOnInit() {
        this.form = this._formBuilder.group({
          albums: this._formBuilder.array([])
        });
        this._albumService.getAllAsFormArray().subscribe(albums => {
          this.form.setControl('albums', albums);
          this.dataSource = new MatTableDataSource((this.form.get('albums') as FormArray).controls);
          this.dataSource.filterPredicate = (data: FormGroup, filter: string) => { 
              return Object.values(data.controls).some(x => x.value == filter); 
            };
        });
        this._userService.getAll().subscribe(users => {
          this.users = users;
        })
      }
    
      get albums(): FormArray {
        return this.form.get('albums') as FormArray;
      }
    
      // On user change I clear the title of that album 
      onUserChange(event, album: FormGroup) {
        const title = album.get('title');
    
        title.setValue(null);
        title.markAsUntouched();
        // Notice the ngIf at the title cell definition. The user with id 3 can't set the title of the albums
      }
    
      applyFilter(filterValue: string) {
        this.dataSource.filter = filterValue.trim().toLowerCase();
      }
    }
    

    HTML

    <mat-form-field>
      <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
    </mat-form-field>
    
    <form [formGroup]="form" autocomplete="off">
        <mat-table [dataSource]="dataSource">
    
          <!--- Note that these columns can be defined in any order.
                The actual rendered columns are set as a property on the row definition" -->
    
          <!-- Id Column -->
          <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef> Id </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.get('id').value}}. </mat-cell>
          </ng-container>
    
          <!-- User Column -->
          <ng-container matColumnDef="userId">
            <mat-header-cell *matHeaderCellDef> User </mat-header-cell>
            <mat-cell *matCellDef="let element" [formGroup]="element">
              <mat-form-field floatLabel="never">
                <mat-select formControlName="userId" (selectionChange)="onUserChange($event, element)" required>
                  <mat-option *ngFor="let user of users" [value]="user.id">
                    {{ user.username }}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </mat-cell>
          </ng-container>
    
          <!-- Title Column -->
          <ng-container matColumnDef="title">
            <mat-header-cell *matHeaderCellDef> Title </mat-header-cell>
            <mat-cell *matCellDef="let element;" [formGroup]="element">
              <mat-form-field floatLabel="never" *ngIf="element.get('userId').value !== 3">
                <input matInput placeholder="Title" formControlName="title" required>
              </mat-form-field>
            </mat-cell>
          </ng-container>
    
          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
    </form>
    <mat-accordion>
      <mat-expansion-panel>
        <mat-expansion-panel-header>
          <mat-panel-title>
            Form value
          </mat-panel-title>
        </mat-expansion-panel-header>
        <code>
          {{form.value | json}}
        </code>
      </mat-expansion-panel>
    </mat-accordion>
    

    【讨论】:

    • 好答案,但 matSort 不起作用我尝试了所有方法,我做了很多搜索以找到解决方案,但我失败了,请你帮我对列应用排序
    • 你好 Snæbjørn:你能帮帮我吗,排序不工作
    • @MohamadChami 过滤器适用于iduserId。不知道为什么它对其他人不起作用。可能是一些内部 ngForm 的东西。
    • 嗨@Snæbjørn 您应用的过滤器不起作用。你有任何对 formControls 有效的过滤器吗?
    【解决方案4】:

    创建一个计算实际索引的函数。

    getActualIndex(index : number)    {
        return index + pageSize * pageIndex;
    }
    

    您可以从分页器获取pageSizepageIndex。然后,在模板中使用这个函数:

    formControlName="getActualIndex(index)"
    

    【讨论】:

    • 这是 IMO 的最佳答案。
    【解决方案5】:

    对于matSort 来说,类型定义很重要,至少我发现是这样。所以在代码中使用任何类型:

    dataSource: MatTableDataSource<any>; 
    

    不会工作。这里必须定义一个类型才能使其工作,尝试定义一个接口并将其传递给MatTableDataSource的泛型。

    另外matColumnDef 必须匹配定义类型的属性名称。

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 2017-09-25
      • 2022-08-23
      • 2018-09-22
      • 2021-04-03
      • 1970-01-01
      • 2019-04-06
      • 2019-10-14
      • 2019-01-04
      相关资源
      最近更新 更多