I want to save the user's data every time they make a change in the input control but not when the page loads. Below is my code:
HTML page:
<form [formGroup]="singleTextForm">
<mat-form-field class="text-box-width">
<input matInput placeholder="" formControlName="AnswersResponses" [ngModel]="AnswersResponses?.answerText" (ngModelChange)="save($event, AnswersResponses)" />
</mat-form-field>
</form>
This is my TypeScript code:
save(event, profileResponse: GetAnswersResponses) {
if (!this.singleTextForm.pristine){
// save data
};
}
The issue I'm facing is that the this.singleTextForm.pristine state doesn't update until the second keystroke. If the user only changes one character, it doesn't trigger the saving process.
Thank you
SOLUTION THAT WORKED
I followed AJT_82's solution with some tweaks. Here is the code I ended up using:
HTML page:
<form [formGroup]="singleTextForm">
<mat-form-field class="text-box-width">
<input matInput placeholder="" formControlName="AnswersResponses" (input)="save(AnswersResponses)" [value]="AnswersResponses.answerText" />
</mat-form-field>
</form>
And here is part of my TypeScript code:
ngOnInit() {
this.singleTextForm.patchValue({
AnswersResponses: this.AnswersResponses
})
}
save(profileResponse: GetAnswersResponses) {
profileResponse.answerText = this.singleTextForm.value["AnswersResponses"].toString();
//saving changes to the database
...
}