Angular 如何添加一个数字大于之前的按钮?

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

我有一个问题,我无法解决那个中等问题。

以下是一些图片:

Picture how it looks now

Picture how it should look like

Picture of how it shouldn't look like

这里的主要问题是,我需要为每个按钮设置一个计数器,但它不能是静态的,因为它会影响每个按钮。

你知道我该如何继续吗?

这是我目前得到的:

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,
    })
  }
}

谢谢你帮我!

您的函数 incrementCount 正在递增所有按钮的计数器:

incrementCount(counter: any) {
  this.counter++;
}

你所有的按钮都链接到同一个变量,当你增加这个变量时,所有按钮的值都会同时增加。

正如 Emilien 所说,如果您想始终递增 1,可以在 *ngFor 中使用索引。

您还可以使用一个数组,在该数组中按特定顺序用您想要的数字填充数组,例如:

var counterArray = [0, 1, 2, 3, 4, 5, ...]

然后在 incrementCount 中,您只需将下一个数字推入数组即可。在你的 html 中你做:

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