角反应形式,仅编辑列表中的选定行

时间:2018-12-19 06:09:12

标签: angular angular-reactive-forms

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

该表单具有一些常规数据(例如,一个人有一个名字和一个姓氏以及一个地址列表)

模板:

<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)不是正确的选择,但我不知道该怎么做。

0 个答案:

没有答案