Reputation: 131
I have a below form group in my student.component.ts:
// Init locals
this.studentFormGroup = this._fb.group({
firstName : ['N/A', {updateOn: 'change'}],
lastName : ['N/A', {updateOn: 'change'}],
address : ['N/A', {updateOn: 'change'}],
phone : ['N/A', {updateOn: 'change'}],
gender : ['N/A', {updateOn: 'change'}],
email : ['N/A', {updateOn: 'change'}],
city : ['N/A', {updateOn: 'change'}],
country : ['N/A', {updateOn: 'change'}],
});
on every control value changes, I do call a webapi and save it to database using the following way. But I don't want to call webapi on gender field though user change its value.
this.studentFormGroup.valueChanges.subscribe(() => this.saveStudentRecord());
Here the problem is the above single line code call saveStudentRecord on every control value change.
But as I mentioned I don't need to call for gender control.
so currently I do follow the below way for value changes for each control
this.studentFormGroup.get('firstName').valueChanges.subscribe(() => this.saveStudentRecord());
this.studentFormGroup.get('lastName').valueChanges.subscribe(() => this.saveStudentRecord());
this.studentFormGroup.get('address').valueChanges.subscribe(() => this.saveStudentRecord());
..
..
and so on except **gender** field
But sometime if I have more controls in a single page I have to write these many statements to just ignore one field.
Is it possible to ignore the gender control value change using the following way?
this.studentFormGroup.valueChanges.subscribe(() => this.saveStudentRecord());
Upvotes: 0
Views: 1640
Reputation: 8002
This is a piece of cake...learn about rxjs and pipeable operators. (Code not tested)
this.studentFormGroup.valueChanges.pipe(
distinctUntilChanged((prev, curr) => prev.gender !== curr.gender)), // don't emit value if gender changed
debounceTime(500), // allow time between keystrokes (computers are too fast sometimes)
takeUntil(this.destroyed$)
).subscribe(() => this.saveStudentRecord());
Upvotes: 3
Reputation: 4006
You can iterate over the keys (with Object.keys()
) in this.studentFormGroup.controls
and call valueChanges.subscribe()
on each control except for the gender control.
Upvotes: 0