Issue
I'm working on an Angular 8 application with Reactive Forms.
I have a form with some controls and I use it for both create and update operations:
this.form = new FormGroup({
id: new FormControl({value: this.editMode ? this.id : '', disabled: false}, [
Validators.required,
this._uniqueIdValidator.bind(this)
]),
label: new FormControl(this.editMode ? this.label : '', [
Validators.required
])
});
The id
control has a custom validator to check its uniqueness:
private _uniqueIdValidator(control: FormControl) {
if (this.collection.findIndex(item=> item.id === control.value) > -1) {
return {duplicate: true};
} else {
return null;
}
}
Now, everything works fine when adding a new item.
However, when I open the form in edit mode, it raises the duplicate
error and I am unable to save the item with the same values as before.
I have added the following code in my validator:
if (this.id !== '' && this.id === control.value) {
// value is identical, so the form is valid
return null;
}
But I'm curious if there is another method to implement it.
Thanks!
Example: Assuming that my data collection is:
[
{id: 'id1', label: 'Foo'},
{id: 'id2', label: 'Bar'},
{id: 'id3', label: 'Another'}
]
and I want to edit the label of the item with id3
, my form raises an error that id field is duplicate.
Solution
I would just extend the if check in the validator to also check if this.id
(if exists) is other than / same as control.value
. I also changed findIndex
to find
here:
private _uniqueIdValidator(control: FormControl) {
if (control.value !== this.id && this.collection.find(item => item.id === control.value)) {
return { duplicate: true };
}
return null;
}
Answered By - AT82
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.