I have a question, I cant solve that medium problem.
Here are some pictures:
Picture how it should look like
Picture of how it shouldn't look like
The main problem here is, that I need a counter for each button, but it can't be static due to the reason that it would affect each button.
Do you have any ideas how I have to proceed?
Here is what I got so far:
app.component.html
<div>
<h2>By click on plus there should be added a new button with a new number</h2>
<div class="item" *ngFor="let item of obj" (click)="addButton()">
<span>{{item.id}}</span>
<span>{{item['count'] ? item['count'] : item['count'] = 0}}</span>
<button (click)="increment(item)">plus</button>
<button (click)="decrement(item)">minus</button>
</div>
</div>
<app-dialog></app-dialog>
<p>Add Button with different number</p>
<h2>{{counter}}</h2>
<div *ngFor="let button of buttons">
<button (click)="addButton()">{{counter}}</button>
</div>
app.component.ts
import { isNgTemplate } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { ShareDataService } from './share-data.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
clickEventsubscription: Subscription
id: number;
title:String;
obj = [{ id: 0, }, { title: 'test' }];
constructor(private share: ShareDataService) {
this.clickEventsubscription = this.share.getClickEvent().subscribe(() => {
this.incrementCount(this.counter);
this.addButton();
})
}
ngOnInit() {
}
counter: number = 0;
incrementCount(counter: any) {
this.counter++;
}
increment(item) {
item.count++;
}
decrement(item) {
item.count--;
}
buttons : {
id : number,
}[] = [{ id : 0}];
// Function to add new button
addButton(){
this.buttons.push({
id : this.buttons.length,
})
}
}
Thanks for helping me out!
Your function incrementCount is incrementing the counter for all buttons:
incrementCount(counter: any) {
this.counter++;
}
All of your buttons are linked to the same variable and as you increment this variable, the value of all buttons will increment simultaniously.
As Emilien said you could use a index in your *ngFor
, if you want to increment always by 1.
You could also make use of an array where you fill the array with the numbers that you want on your buttons in the specific order, e.g.:
var counterArray = [0, 1, 2, 3, 4, 5, ...]
and then in incrementCount you simply push the next number to the array. And in your html you do:
<div *ngFor="let numb of counterArray ">
<button (click)="addButton()">{{ numb }}</button>
</div>