11

注意:我成功地在经典 HTML 表中执行 FormArray,如下所示。我想在 Angular Material 表中有一个 FormArray 并用数据填充它。我尝试了与经典 HTML 表相同的方法,但由于错误“找不到带有 id 'name'' 的列” ,我无法编译它

<div class="form-group">
<form [formGroup]="myForm" role="form">
  <div formArrayName="formArrList">
    <table>
      <tr>
        <th>Name</th>
        <th>School</th>

      </tr>

      <tr *ngFor="let list of myForm.get('formArrList').controls;let i = index" [formGroupName]="i">
        <td>
          <div class="col-sm-6">
            <input class="form-control" type="text"  formControlName="name"/>
          </div>
        </td>
        <td>
          <div class="col-sm-6">
            <input class="form-control" type="text"  formControlName="school"/>
          </div>
        </td>
      </tr>
    </table>
  </div>
</form>

我尝试在我的 Angular Material Table 中有一个 FormArray 这是我的 HTML 文件

<div>
<form [formGroup]="myForm" role="form">
  <ng-container formArrayName="formArrList">

  <mat-table #table [dataSource]="myDataSource">
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>


    <ng-container *ngFor="let detailsItems of myForm.get('formArrList').controls;let i = index" [formGroupName]="i">


    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
      <mat-cell *matCellDef="let element"> 

        <mat-form-field class="" hideRequiredMarker>
      <input matInput formControlName="name" type="text" class="form-control"
             autocomplete="off"
             placeholder="name">
      </mat-form-field>

      </mat-cell>
    </ng-container>



    <ng-container matColumnDef="school">
      <mat-header-cell *matHeaderCellDef>School</mat-header-cell>
      <mat-cell *matCellDef="let element"> 

       <mat-form-field class="" hideRequiredMarker>
      <input matInput formControlName="school" type="text" class="form-control"
             autocomplete="off"
             placeholder="school">
      </mat-form-field>
      </mat-cell>
    </ng-container>

    </ng-container>



  </mat-table>
  </ng-container>

</form>

这是我的 .TS 文件的一部分

@Component(..)
export class DemO implements OnInit {

 displayedColumns = ['name', 'school'];
  myForm: FormGroup;

  formArrList: FormArray;

   myDataSource: DataSource;
   dummyData: Element[] = [];


   ngOnInit(): void {

    //init form arrayTree
    this.myForm = this.formBuilder.group({
      'formArrList': new FormArray([])
    });

  }

    initTreeFormArray(name: string, school: string) {
    return this.formBuilder.group({
      'name': [code_any,],
      'school': [prio,]
    });
  }


  renderTableOnButtonClick(){
       const control = <FormArray>this.treeForm.controls['formArrList']; 
       control.push(this.initTreeFormArray("DummyName", "DummySchool", element.name));



      this.dummyData.push({name: "DummyName", school: "DummySchool"});
      this.myDataSource = new sDataSource(this.dummyData);


}
4

4 回答 4

4

聚会有点晚了,但我设法让它发挥作用。

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>
于 2019-05-20T13:48:53.040 回答
1

initTreeFormArray()不会按照您需要的方式在 init 上触发。因此,当组件构建时,html 部分会在名称不存在时查找名称。

我的 .02 是在 init 上加载一个工作表单和子表单组,然后再找出第二个函数。另外,在 html 表上使用 Mat。

于 2018-02-06T21:53:05.343 回答
0

在 Angular 9 中,要使 Material Table 使用 FormArray 作为数据源。

我创建了接口来定义类型,MatTableDataSource<Type>还创建了该接口对应字段的形式。然后,当您需要初始化数据源时,您可以分配form array value. 我将 getter 用于 Form Array,然后我将其称为:this.myGetter.value.

下面是代码:

宣言

dataSource = new MatTableDataSource<MyInterface>();

初始化方法

// I call this method whenever a change occur in FormArray
initializeMyDataSource() {
    this.dataSource = new MatTableDataSource<MyInterface>(this.myGetter.value);
}

我的吸气剂

get myGetter(): FormArray {
    return (this.myFormGroup.get('myFormArray') as FormArray);
  }

我的界面

export interface MyInterface {
  fieldA: string;
  fieldB: number;
}

我的表单组

this.formBuilder.group({
  fieldA: [''],
  fieldB: ['']
})

在 HTML 中,只需像通常对 MatTable 一样使用 dataSource。基本上,当您.value在 formGroup 或 formArray 的末尾使用时,它会返回一个普通对象,在这种情况下,它将是 MyInterface 对象,也是此 MatTable 的类型。

在这里,您可以遵循 matTable 指南。确保在应用 formArray 之前先使用虚拟数据检查它,以确保错误来自何处。

希望有帮助!

于 2020-04-24T02:00:31.440 回答
0

可能您在这里不需要控件

myForm.get('formArrList').controls

尝试使用

myForm.controls.formArrList.controls

or

myForm.get('formArrList')
于 2018-07-27T12:23:24.667 回答