[Fixed] Angular how to add a button with a number greater than before?


I have a question, I cant solve that medium problem.

Here are some pictures:

Picture how it looks now

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:


  <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['count'] ? item['count'] : item['count'] = 0}}</span>
    <button (click)="increment(item)">plus</button>
    <button (click)="decrement(item)">minus</button>

<p>Add Button with different number</p>

<div *ngFor="let button of buttons">
  <button (click)="addButton()">{{counter}}</button>


import { isNgTemplate } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { ShareDataService } from './share-data.service'

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
export class AppComponent {
  clickEventsubscription: Subscription

  id: number;

  obj = [{ id: 0, }, { title: 'test' }];

  constructor(private share: ShareDataService) {
    this.clickEventsubscription = this.share.getClickEvent().subscribe(() => {
  ngOnInit() {
  counter: number = 0;
  incrementCount(counter: any) {

  increment(item) {
  decrement(item) {

  buttons : {
    id    : number,
}[] = [{ id : 0}];

// Function to add new button
        id    : this.buttons.length,

Thanks for helping me out!


Your function incrementCount is incrementing the counter for all buttons:

incrementCount(counter: any) {

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>

Leave a Reply

(*) Required, Your email will not be published