Consider an Angular reactive form with an input. Whenever the input changes, we want to keep its old value and display it some where. the following code does it as displayed:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Reactive Form';
changedValue;
oldValue;
ooldValue;
rform = new FormGroup({
inputOne: new FormControl('chang me')
});
onOneChange(event) {
this.changedValue = event.target.value;
console.log('oneChanged', this.changedValue, 'old value is', this.oldValue);
this.ooldValue = this.oldValue;
setTimeout( ()=>this.oldValue = this.changedValue, 1);
}
}
<form [formGroup]="rform">
<label>
One:
<input formControlName="inputOne" (change)="onOneChange($event)"/>
</label>
</form>
<p>
changed value: {{changedValue}}
</p>
<p>
old value: {{ooldValue}}
</p>
As you can see it has been addressed by keeping three variables in the code which is not desirable (Yes the changedValue
variable can be removed, but still two variables to keep the old value is annoying, isn't it?).
Is there any way to rewrite the code with less variables? Does Angular itself has a descent way to do that?
You can find the code here