I am iterating over an array in typescript to take a snapshot of a div having id equal to the index of the array and download an image file.
If the array was having 2 rows, 2 images should be downloaded. Here is the script:
public toCanvas() {
let i = Object.keys(this.array).length;
Object.keys(this.array).forEach((key, index)=>{
var elem = document.getElementById(index.toString());
console.log(index)
html2canvas(elem).then(function(canvas) {
var generatedImage = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href=generatedImage;
});
})
}
Using Object.keys(this.array).forEach((key, index)
, I am iterating to get the index, and then find the document getElementId(index)
.
The problem is that it always download the last image.
And at the console, the indexes are consoled, at the beginning and then the image is downloaded:
The html script:
<mat-card [id]="i" *ngFor="let arrayOfData of array; let i=index; " class="example-card" #matCard>
I tried using while
inside forEach()
:
public toCanvas() {
let i = Object.keys(this.array).length;
Object.keys(this.array).forEach((key, index) => {
while (i != -1) {
i--;
console.log(i)
var elem = document.getElementById(index.toString());
html2canvas(elem).then(function (canvas) {
var generatedImage = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href = generatedImage;
});
}
})
}
And it's doing the same behavior. It consoles the index until it reaches to 0
and then downloads the image of the last detected <mat-card>
EDIT
Here is a stackblitz of the recursive method provided by @xyz.