编辑 - 正如 Eliseo 在 cmets 中指出的那样,您可以将 Pairwise 运算符用于 make this even easier。
我这样做的方法是创建一个FormGroup,迭代我的属性列表添加每个控件,然后订阅每个控件ValueChanges observable。 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.