首页 > 解决方案 > 角度反应形式,仅编辑列表中的选定行

问题描述

我正在尝试使用数组构建动态 Angular Reactive Form。我想要的是显示一个包含静态数据(不可编辑)的表格,并在每一行上都有一个编辑/删除图标。当用户单击编辑按钮时,选定的行数据将显示在表格下方的 dit 形式中。

表格有一些一般数据(例如,一个人有名字和姓氏以及地址列表)

模板:

<form [formGroup]="placesForm" class="card mx-4" (submit)="onSubmit()">
    Firstname <input class="form-control" formControlName="firstName" />
    Lastname <input class="form-control" formControlName="lastName" />

    Your addresses :
    <table class="table table-striped" >
      <tr *ngFor="let place of placesForm.get('places').controls; let i=index">
        <td>{{i}}</td>
        <td>{{place.get('street').value}}</td>
        <td>{{place.get('city').value}}</td>
        <td>{{place.get('zipCode').value}}</td>
        <td width="35"><i class="icon-pencil" (click)="editPlace(i)" title="Edit"></i> <i class="icon-trash" (click)="removePlace(i)" title="Delete"></i> </td>
      </tr>
    </table>
    <div *ngIf="selectedPlace">
        <app-address-form [addressForm]="placesForm.get('places').at(selectedPlace)"></app-address-form>
    </div>
</form>

组件:

export class Step2PlacesComponent implements OnInit {
  private placesForm: FormGroup;
  private selectedPlace = 0;

  constructor(
    private fb: FormBuilder,
  ) {
  }

  ngOnInit() {
    this.placesForm = this.fb.group({
      firstName: [null],
      lastName: [null],
      places: this.fb.array([this.fb.group({
          street: [null, Validators.required],
          city: [null, Validators.required],
          zipCode: [null, Validators.pattern(/\d+/)]
        })])
    });
  }

  onSubmit() {
  }

  addPlace() {
      places.push(this.fb.group({
          street: [null, Validators.required],
          city: [null, Validators.required],
          zipCode: [null, Validators.pattern(/\d+/)]
        }));
  }

  editPlace(index) {
    this.selectedPlace = index;
  }

  removePlace(index) {
    let places = (<FormArray>this.placesForm.get('places'));
    places.removeAt(index);
    if (this.selectedPlace >= places.controls.length) {
      this.selectedPlace --;
    }
  }
}

app-address-form模板:

<div [formGroup]="addressForm">
    <input class="form-control" formControlName="street" />
    <input class="form-control" formControlName="city" />
    <input class="form-control" formControlName="zipCode" />
</div>

app-address-form组件:

export class AddressFormComponent implements OnInit {
    @Input() addressForm: FormGroup;

    constructor() {
    }

    ngOnInit() {
    }
}

当我单击编辑按钮时, selectedPlace 会相应更新,但 app-address-form 组件未更新,我仍在编辑第一行。

也许placesForm.get('places').at(selectedPlace)不是正确的做法,但我不知道该怎么做。

标签: angularangular-reactive-forms

解决方案


推荐阅读