Reputation: 5075
I am working Angular 2 form and have drop-down/ select in template whose data is bind with ngModel and onChnage event. I need to detect previous value of ngModel? I have tried with data-* attributes https://www.w3schools.com/tags/att_global_data.asp to store current value in it, hoping it won't change with ngModel value, followed by send back when event fire but getting NaN value when it pass on change.
drop-down / select initial values are mapped from array that is question[], current defaultValue is in "question.value"
<div *ngSwitchCase="'dropdown'"> <small>dropdown</small>
<div class="form-group">
{{question.value}}
<select [id]="question.key"
[formControlName]="question.key"
[(ngModel)]="question.value"
data-default-element="question.value"
(change)="onChangeValue($event, responseId, question.key, data-default-element , 'dropdown')"
(blur)="onChangeValue($event, responseId, question.key, data-default-element , 'dropdown')"
>
<option *ngFor="let opt of question.options"
[value]="opt.key" >{{opt.value}} </option>
</select>
</div>
</div>
onChangeValue(event: any, givenResponseId:string, givenQuestionId:string, defaultValue:string, givenInputType:string) {
var givenAnswer = null;
console.log("defaultValue ",defaultValue);
if(event.target.value !="")
{
givenAnswer = event.target.value;
console.log("newValue ",givenAnswer );
}
}
Upvotes: 1
Views: 8796
Reputation: 1559
You must consider using OnChanges from '@angular/core'. With this you can get the current and the previous value. Here is an example. Notice that it only works on attribute of type Input
import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';
@Component({
selector: 'app-your-selector',
templateUrl: './template-path.html',
styleUrls: ['./style-path.css']
})
export class myComponent implements OnChanges{
@Input() myAttribute : string;//This should be your ngModel attribute
ngOnChanges(changes : SimpleChanges ){
if(changes["myAttribute"]){
let currentValue = changes["myAttribute"].currentValue;
let previousValue = changes["myAttribute"].previousValue;
}
}
}
Upvotes: 2
Reputation: 11399
If you remove the ngModel
from your form, and pass question.value
instead of data-default-element
to your change method, you will get the previous value. Then, you can update question.value
in your change-method to update it with the given answer if you want to. The ngModel
will two-way bind the data, making your question.value being updated when the user enters something in the form.
Upvotes: 0