I've been troubleshooting this problem for a while now and I'm hoping that someone here can assist me with finding a solution.
The issue at hand involves an array object containing various values such as id, title, amountCounter
. Specifically, the amountCounter is supposed to increment when a button is clicked, but it fails to decrement when the object is removed from the array.
To provide a clearer picture of the problem, I have included a couple of screenshots:
Here is the image after several clicks on ID 1:
https://i.sstatic.net/bMmOr.png
And here is the image after clicking "X" to remove the object:
https://i.sstatic.net/bjyp0.png
From the images, you can see that the amountCounter
in the array increases by 29.99 each time, but does not decrease by 29.99 when the object is removed. I'm struggling to understand why this is happening.
Your help in resolving this issue would be greatly appreciated. Here are the relevant files:
app.component.html
<app-dialog></app-dialog>
<h2>Add values of my service into array:</h2>
<p>Array:</p>
<p>Total: {{amountCounter}}</p>
<div *ngFor="let item of data, let i = index;">
<span>ID: {{item.id}}</span>
<span>Title: {{item.title}}</span>
<span id="remove" (click)="removeElement(i)" class="material-icons">
Click me to remove and decrement the "amountCounter by 29.99"
</span>
</div>
app.component.ts
export class AppComponent {
clickEventsubscription: Subscription;
ngOnInit() {}
id: number;
title: String;
amountCounter: number;
isClicked: boolean = false;
data: any = [];
constructor(private share: ShareDataService) {
this.clickEventsubscription = this.share.getClickEvent().subscribe(() => {
this.initialize();
});
}
removeElement(index: number) {
this.data.splice(index, 1);
}
test() {}
initialize() {
this.id = this.share.getId();
this.title = this.share.getTitle();
this.amountCounter = this.share.getAmountCounter();
const newData = {
id: this.id,
title: this.title,
amountCounter: this.amountCounter
};
this.data.push(newData);
console.log(this.data);
}
}
share-data-service.ts
private subject = new Subject<any>();
title: String;
id: number;
amountCounter: number;
getId() {
return this.id;
}
getTitle() {
return this.title;
}
getAmountCounter() {
return this.amountCounter;
}
sendClickEvent() {
this.subject.next();
}
getClickEvent(): Observable<any> {
return this.subject.asObservable();
}
I've also created a StackBlitz for more insight into the issue:
https://stackblitz.com/edit/angular-ivy-shdyrw?file=src%2Fapp%2Fshare-data.service.ts
Thank you for your assistance.