I have a object
formErrors = {
'name': [],
'age' : []
};
I am adding validation errors to it Dynamically from a Template Driven form . But when i try to push values to the key it throws errors and when i just assign it a normal string it works.
onValueChanged(data?: any) {
if (!this.f) { return; }
const form = this.f.form;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field].push(messages[key]); // error line
this.formErrors[field] += messages[key] + ' '; // this works if the change object struct to name :''
}
}
}
}
The error in console is
TemplateDrivenComponent.html:10 ERROR TypeError: this.formErrors[field].push is not a function
at
TemplateDrivenComponent.webpackJsonp.178.TemplateDrivenComponent.onValueChanged (template-driven.component.ts:46)
at template-driven.component.ts:29
at SafeSubscriber.schedulerFn [as _next] (core.es5.js:3840)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:236)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at EventEmitter.Subject.next (Subject.js:55)
at EventEmitter.emit (core.es5.js:3814)
at FormGroup.AbstractControl.updateValueAndValidity (forms.es5.js:2601)
at FormControl.AbstractControl.updateValueAndValidity (forms.es5.js:2605)
at FormControl.setValue (forms.es5.js:2948)
at DefaultValueAccessor.onChange (forms.es5.js:1752)
at DefaultValueAccessor._handleInput (forms.es5.js:619)
at Object.eval [as handleEvent] (TemplateDrivenComponent.html:10)
this.formErrors[field] = ''; push works on array & Not String.this.formErrors[field] = '';I think you meant an empty array to "clear errors"[].this.formErrors[field] = []