Reputation: 327
I was trying to implement ngOnChanges() to capture previous and current value. The function I have implemented works fine. I am able to see previous and current value in the console but I am getting this error even though my code is compiling successfully. I am getting the same error for "propertyName", "change", "current" and "previous". If I use 'const' instead of 'let' then my function doesn't work. Please help!!
Code:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-simple',
templateUrl: './simple.component.html'
})
export class SimpleComponent implements OnChanges {
@Input() simpleInput: string;
ngOnChanges(changes: SimpleChanges) {
for (let propertyName in changes) {
let change = changes[propertyName];
let current = JSON.stringify(change.currentValue);
let previous = JSON.stringify(change.previousValue);
console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
}
}
}
Upvotes: 0
Views: 3313
Reputation: 87
There is another way to iterate array. Using of in advanced for loop.
Try using for (let propertyName of changes){}
This might help you.
Edit1: If a variable is never reassigned, using the const declaration is better. https://eslint.org/docs/rules/prefer-const Try like this:
ngOnChanges(changes: SimpleChanges) {
for (const propertyName in changes) {
if (changes[propertyName]) {
const change = changes[propertyName];
const current = JSON.stringify(change.currentValue);
const previous = JSON.stringify(change.previousValue);
console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
}
} }
Upvotes: 1
Reputation: 3031
This is an ESlint error: https://eslint.org/docs/rules/prefer-const
Your code will work fine, because there is nothing wrong with it programatically, it is just not good for readability as noted in the link I have provided. If you don't want to see the error, you can disable it in your tslint.json file. You can do this manually OR use the third option from the error dialog i.e. 'Remove rule prefer-const
from tslint.json'.
Upvotes: 1