I am trying to load an image dynamically in angular, so that there is no image caching. However, I am seeing this error in console when I try the following in angular:
ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError:
Expression has changed after it was checked.
Previous value for 'src': 'assets/my-image.svg?1662363097161'.
Current value: 'assets/my-image.svg?1662363097162
Code inside HTML file:
<img [src]="getImagePath()" width="500"/>
Code inside Angular Component
getImagePath() {
const imagePath = `assets/my-image.svg?${Date.now()}`;
return imagePath;
}
How do I make sure the SVG is not cached and I don't see the console error?
CodePudding user response:
From angular errors.
In development mode, Angular performs an additional check after each change detection run, to ensure the bindings haven't changed. This catches errors where the view is left in an inconsistent state. This can occur, for example, if a method or getter returns a different value each time it is called, or if a child component changes values on its parent.
I don't really have that much experience in angular, but I'd wager that binding your src
to a variable instead of a function and then setting that variable in ngOnInit
should work.
In your component
imagePath: string = "";
ngOnInit(): void {
this.imagePath = `assets/my-image.svg?${Date.now()}`;
}
Template
<img [src]="imagePath" width="500"/>
CodePudding user response:
You are trying to circumvent caching by appending the current timestamp to the URL, that's a usual way to do it. BUT since angular checks if the value change and that Date.now() always changes, you get the error you see.
What you could do is store Date.now() on a component property so it does not change after initialized.
Better yet, set the correct headers on your SVG so that it does not get cached by the browser, without having to fool it like you are trying to do.