1 year ago

#77516

test-img

Desenv Junior

Angular material table not showing data when using formarray of reactive form

So, I'm trying to create a table with reactive form and form arrays, I can add data into my form, but I can't see the table.

I'm using angular material table.

I already have a question(Error: Cannot read properties of undefined (reading 'headerCell') - Creating reactive form inside a angular material table) but this time I don't have any error in my console.

HTML

<button mat-button mat-raised-button (click)="addParameterWhatsApp()" color="primary">Add</button>

<form [formGroup]="form" autocomplete="off">

  <table #table mat-table [dataSource]="dataSource" class="mat-elevation-z8" formGroupName="whatsapp">
    <ng-container formArrayName="parameters">

      <ng-container matColumnDef="posicao">
        <th mat-header-cell *matHeaderCellDef> Posicao </th>
        <td mat-cell *matCellDef="let element">
          <mat-form-field appearance="outline">
            <mat-label>Posicao</mat-label>
            <input matInput formControlName="posicao" />
          </mat-form-field>
        </td>
      </ng-container>

      <ng-container matColumnDef="valor">
        <th mat-header-cell *matHeaderCellDef>Valor</th>
        <td mat-cell *matCellDef="let element">
          <mat-form-field appearance="outline">
            <mat-label>Valor</mat-label>
            <input matInput formControlName="valor" />
          </mat-form-field>
        </td>
      </ng-container>

    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; let i = index, columns: displayedColumns;" [formGroupName]="i"></tr>
  </table>
</form>

{{form.value | json}}

TS

form!: FormGroup;
  dataSource;
  displayedColumns = ['posicao', 'valor'];
  constructor(private _formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.createForm();
  }

  createForm() {
    this.form = this._formBuilder.group({
      whatsapp: this._formBuilder.group({
        name: [],
        parameters: this.buildArrayParametersWhatsApp(),
      }),
    });
  }

  get parameters() {
    return this.form.get('whatsapp')?.get('parameters') as FormArray;
  }

  buildArrayParametersWhatsApp() {
    return this._formBuilder.array([]);
  }

  addParameterWhatsApp() {
    const parametersArray = this._formBuilder?.group({
      posicao: [],
      valor: [],
    });

    if (parametersArray) {
      this.parameters.push(parametersArray);
    }
  }

If I change my datasource:

dataSource = [ { posicao: 1, valor: 2 } ]

it's me return the error

TypeError: Cannot read properties of null (reading '_rawValidators')

angular

angular-material

angular-reactive-forms

mat-table

0 Answers

Your Answer

Accepted video resources