Validator on add and without clearing (ngx-chips, angular)
Ultimately the awkward implementation of this control makes things difficult. If it were a ControlValueAccessor with a model that includes the current input and array of tags, it would be a much simpler matter to find a solution.
As with @AlesD's answer, I went with a solution that utilizes onAdding
. One issue he brings up is the problem with using this
. To get around that problem I use the bind()
function when necessary.
In order to implement your desired behavior I did three things:
- Modify the validator function so that it would only return an error if a field addFirstAttemptFailed was true. This will prevent the validator for executing.
- Add a callback to
onAdding
. It validates the tag, and if the validation fails, sets addFirstAttemptFailed to true and returns an error observable (I upgraded to rxjs 6). Throwing this error prevents the tag from being added. - Once an item is successfully added addFirstAttemptFailed is set back to false so the behavior can begin again for the next tag.
Unfortunately the method that is called during onAdding has some rigs.
- In order to get validation to occur, I had to get a reference to chip's TagInputComponent and call
setInputValue()
, passing the value that's already set. Believe me I tried a thousand variants before I stumbled upon this side effect. Trying to callupdateValueAndValidty()
on either the FormControl instance on your component or various instances of Form and FormControl within the TagInputComponent never quite worked. - In order to prevent adding (and not have the input get cleared), I have to return an error observable from
throwError()
. Unfortunately the way the subscription is setup internally is that the TagInput component only callscatchError()
on it's subscription callback function, not on the source observable. So the error gets displayed in the console. Again - I tried a bunch of different ways to get around it.
Relevant code
@ViewChild('tagInput')
tagInput: SourceTagInput;
public validators = [ this.must_be_email.bind(this) ];
public errorMessages = {
'must_be_email': 'Please be sure to use a valid email format'
};
public readonly onAddedFunc = this.beforeAdd.bind(this);
private addFirstAttemptFailed = false;
private must_be_email(control: FormControl) {
if (this.addFirstAttemptFailed && !this.validateEmail(control.value)) {
return { "must_be_email": true };
}
return null;
}
private beforeAdd(tag: string) {
if (!this.validateEmail(tag)) {
if (!this.addFirstAttemptFailed) {
this.addFirstAttemptFailed = true;
this.tagInput.setInputValue(tag);
}
return throwError(this.errorMessages['must_be_email']);
}
this.addFirstAttemptFailed = false;
return of(tag);
}