Saltar al contenido

Tabla editable de material angular usando FormArray

Solución:

Usaría el índice que podemos obtener dentro matCellDef vinculante:

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

Stackblitz bifurcado

Para resolver problemas de clasificación y filtrado, eche un vistazo a esta respuesta Clasificación de tabla de material angular con formarray reactivo

Aquí está el código de ejemplo

En 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>

Código del controlador:

    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]
        });
      }

Un poco tarde para la fiesta, pero logré hacerlo funcionar sin depender del índice. Esta solución también admite el filtrado, etc. de la MatTableDataSource.

Componente

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>
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *