Lint error message:
src/app/detail/edit/edit.component.ts[111, 5]: for (... in ...) statements must be filtered with an if statement
Code snippet (It is a working code. It is also available at angular.io form validation section):
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] += messages[key] + ' ';
}
}
}
Any idea how to fix this lint error?
This question is related to
angular
angular2-forms
angular-cli
tslint
use Object.keys:
Object.keys(this.formErrors).map(key => {
this.formErrors[key] = '';
const control = form.get(key);
if(control && control.dirty && !control.valid) {
const messages = this.validationMessages[key];
Object.keys(control.errors).map(key2 => {
this.formErrors[key] += messages[key2] + ' ';
});
}
});
A neater way of applying @Helzgate's reply is possibly to replace your 'for .. in' with
for (const field of Object.keys(this.formErrors)) {
for (const field in this.formErrors) {
if (this.formErrors.hasOwnProperty(field)) {
for (const key in control.errors) {
if (control.errors.hasOwnProperty(key)) {
If the behavior of for(... in ...) is acceptable/necessary for your purposes, you can tell tslint to allow it.
in tslint.json, add this to the "rules" section.
"forin": false
Otherwise, @Maxxx has the right idea with
for (const field of Object.keys(this.formErrors)) {
I think this message is not about avoiding to use switch
. Instead it wants you to check for hasOwnProperty
. The background can be read here: https://stackoverflow.com/a/16735184/1374488
Source: Stackoverflow.com