I have dynamic select boxes for different properties which get populated in the form. Before on change event I want to store the array of selected property values from the dropdown. (properties => array with multiple dropdown values under a property)
<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>
I tried using focus to store old value but its providing only current selected value.
Any help will be appreciated.
Edit - as Eliseo pointed out in the comments, you can use the Pairwise operator to make this even easier.
The way I'd do this is to create a FormGroup, iterate my properties list adding each control and then subscribe to each controls ValueChanges observable. What's nice about ValueChanges
is that the event triggers before the value is updated, so you can easily access the current value and what the value will be.
Here's an example:
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];
});
});
}
}
And the template:
<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>