在 angular 表单中的更改事件之前,将之前的 selected 值存储在 select 框中

Store previous selected values in select box before on change event in angular forms

我有不同属性的动态 select 框,这些框会填充到表单中。在发生更改事件之前,我想从下拉列表中存储 selected 属性 值的数组。 (properties => array with multiple dropdown values under a 属性)

<div *ngFor="let p of properties; let i = index">
    <ng-select placeholder="Select" (change)="onChange($event)">
            <ng-option *ngFor="let value of p.values" [value]="value">{{value.value}}</ng-option>
          </ng-select>
</div>

我尝试使用焦点来存储旧值,但它仅提供当前 selected 值。

如有任何帮助,我们将不胜感激。

Edit - 正如 Eliseo 在评论中指出的那样,您可以使用 Pairwise operator to make this even easier.

我这样做的方法是创建一个 FormGroup, iterate my properties list adding each control and then subscribe to each controls ValueChanges 可观察对象。 ValueChanges 的优点是事件在值更新之前触发,因此您可以轻松访问当前值以及该值将是什么。

这是一个例子:

export class AppComponent {
  form: FormGroup = new FormGroup({});
  previousValues = {};

  properties: any[] = [
    {
      label: "Favorite Animal",
      values: ["cat", "dog", "bird", "bunny"]
    },
    {
      label: "Favorite Vehicle",
      values: ["car", "boat", "motorcycle", "hot air balloon"]
    },
    {
      label: "Favorite Element",
      values: ["earth", "air", "fire", "water"]
    }
  ];

  ngOnInit() {
    this.properties.forEach(prop => {
      this.form.addControl(prop.label, new FormControl(""));
      this.previousValues[prop.label] = "";

      this.form.controls[prop.label].valueChanges.subscribe(evt => {
        this.previousValues[prop.label] = this.form.value[prop.label];
      });
    });
  }
}

和模板:

<form [formGroup]="form" *ngFor="let p of properties; let i = index">
    <label>{{i}}: </label>
    <select placeHolder="Select" [formControlName]="p.label">
    <option [value]="opt" *ngFor="let opt of p.values">
      {{opt}}
    </option>
  </select>
</form>

<div class="form-value">
    <label>Current Values:</label>
    {{form.value | json}}
</div>

<div class="form-value">
    <label>Previous Values:</label>
    {{previousValues | json}}
</div>

Here's a stackblitz that demonstrates.