Forms 输入控制中的第二个按键行程后,角度4形状状态发生变化
我想在每次更改输入控件时保存用户的数据。但我不想在页面加载时保存。这是我的密码: HTML页面:Forms 输入控制中的第二个按键行程后,角度4形状状态发生变化,forms,angular,typescript,Forms,Angular,Typescript,我想在每次更改输入控件时保存用户的数据。但我不想在页面加载时保存。这是我的密码: HTML页面: <form [formGroup]="singleTextForm"> <mat-form-field class="text-box-width"> <input matInput placeholder="" formControlName="AnswersResponses" [ngModel]="AnswersResponses?.answerT
<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>
<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>
它工作得很好,只是this.singleTextForm.pristine状态直到第二次击键时才会更新。因此,如果用户只想更新一个字符,应用程序将不会保存它
谢谢
工作解决方案
因此,我采用了AJT_82解决方案,并进行了一些更新。以下是我使用的代码:
HTML页面:
<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>
<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>
试着检查它是否脏<代码>!这个.singleTextForm.dirty我会稍微修改一下,充分利用反应式表单,从而完全删除
ngModel
。如果您正在向变量应答
(非formcontrol)接收数据,您可以在接收数据时使用补丁值
或设置值
将值设置为表单控件:
this.singleTextForm.patchValue({
AnswersResponses: this.AnswersResponses.answerText
})
然后,我们可以删除ngModelChange
,而是监听用户的input
:
<input matInput formControlName="AnswersResponses" (input)="save()" />
作为旁注,如果您正在进行一个http保存调用,您可能希望对其进行更多的更改,并使用
valueChanges
听取formcontrol的更改,并使用debounceTime
和distinctUntilChanged
,例如,对于用户键入速度非常快而不使“不必要”的用例http调用。所以我终于让它工作了,但我不得不修改您的代码,以便传递对象,而不仅仅是文本(我还在学习),请参见我更新的问题。至于你的旁注,我想到了,但我不知道怎么做,你能告诉我一个网站的工作示例吗?谢谢你的帮助。这里有一个演示,选择你想要的去盎司时间,发出http请求(注释掉)并订阅!:)这个答案给了我和我的问题一样的结果
save() {
console.log(this.singleTextForm.value)
}