I have an angular 7 project where I display a gallery of images in one component and I have all the images in assets/images folder. Every image have its own button to delete and I have the delete()
function empty cause I don´t know how to delete the image from the component.
I've being searching around but all I found is people asking how to access to the images but not how to delete them. I appreciate any help.
EDIT: In this moment I delete the images from the visualization but I also want to delete it from the folder I locally have.
EDIT:
You can't delete files from the user's computer or from the server using JS in the browser. You should send an http request to a server that will do that for you.
But deleting files is rare, especially for an app with no user management and any other backend (otherwise you wouldn't be asking how to do it in angular). I think you should rethink what you are doing.
If all you want is to hide the image from the user 'forever', you can use localStorage to store the deleted images and filter the images out on every reload.
You are having multiple images, and you want them dynamic, so you should move it to the JS side of the component, and use the html just to display it. So you should create an array that will contain the images, for example:
public images = ['imagePath1', 'imagePath2', 'imagePath3'];
Or, if you have more information related to the images, you can use objects
public images = [{path: 'imagePath1', description: 'image 1'}, {path: 'imagePath2', description: 'image 2'}];
Then, in the html, use ngFor and variables to display the images:
<div *ngFor="let image of images">
<img [src]="image.path" [alt]="image.description" />
<small>{{image.description}}</small>
</div>
And don't forget to add the button, and you should pass it the index of the image so you'll know which image to remove from the array:
<div *ngFor="let image of images; let i = index">
<img [src]="image.path" [alt]="image.description" />
<small>{{image.description}}</small>
<button (click)="remove(i)">remove this image</button>
</div>
and now we can start working on the remove function. Go back to your JS code and add the index parameter. Inside the function, simply remove the index from the array and the image will disappear.
public remove(index: number) {
this.images.splice(index, 1);
}
And that's it!
If you want to be permanently remove the image, it's more complicated. You should have a server, and should send an http request on remove to let it know that you want an image to be removed, and it will handle the real image deletion.