[英]How to check if each form control changed their value in reactive forms?
What I want to achieve in the end is to see which form controls individually from my form have changed and to create a new object with them assigning a boolean of true if they were changed or false if not.我最终想要实现的是查看我的表单中的哪些表单控件已更改,并创建一个新的 object,如果它们被更改,则分配 boolean 为 true,否则为 false。 Please see below what I achieved so far, but I don't think this the right approach as when I'll have more from controls my method will become gigantic.
请看下面我到目前为止所取得的成就,但我认为这不是正确的方法,因为当我从控件中获得更多时,我的方法将变得巨大。 If you guys have any idea how I can approach this I would really appreciate it.
如果你们知道我该如何解决这个问题,我将不胜感激。
my Html我的 Html
<form [formGroup]="editProfileForm">
<ion-row>
<ion-col>
<ion-input
*ngIf="profileData"
formControlName="firstName"
placeholder="First Name"
></ion-input>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-input
*ngIf="profileData"
formControlName="lastName"
placeholder="Last Name"
></ion-input>
</ion-col>
</ion-row>
</form>
<ion-fab
vertical="bottom"
horizontal="center"
slot="fixed"
(click)="onSubmitEditedProfile()">
<ion-fab-button>
<ion-icon name="checkmark-outline"></ion-icon>
</ion-fab-button>
</ion-fab>
my TS我的 TS
onSubmitEditedProfile() {
if (this.profileData !== null) {
let updatedFirstName = this.editProfileForm.get("firstName").value;
if (this.profileData.firstname !== updatedFirstName) {
}
console.log("it's the same");
} else {
console.log("it's different")
}
And as my approach means, I'll do the same for lastName
and so on正如我的方法的意思,我会为
lastName
做同样的事情等等
Here is the example where you can iterate each form control and identify either its changed or not based on that populate new array of object.这是一个示例,您可以在其中迭代每个表单控件并根据填充的 object 新数组来识别它是否已更改。
onSubmitEditedProfile() {
const formValue = [];
// iterate over form controls no matter how many control you have.
Object.keys(this.form.controls).map((key) => {
// create a new parsed object
const parsedValue = {
[key]: this.form.get(key).value, // key is the actual form control name
changed: this.form.get(key).dirty // added changed key to identify value change
}
// push each parsed control to formValue array.
formValue.push(parsedValue)
})
console.log(formValue)
}
Here is the stackblitz working DEMO这是 stackblitz 工作演示
Hope this address your requirements.希望这能满足您的要求。
All you need is just to read dirty value on FormGroup or individual FormControl您只需要读取 FormGroup 或单个 FormControl 上的脏值
https://angular.io/api/forms/AbstractControl#dirty https://angular.io/api/forms/AbstractControl#dirty
onSubmitEditedProfile() {
if (!this.editProfileForm.dirty) {
console.log("it's the same");
} else {
console.log("it's different")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.