【问题标题】:Add or subtract quantity as you click on the row of a table单击表格的行时添加或减去数量
【发布时间】:2023-01-23 18:17:05
【问题描述】:

我需要当我点击表格的行时添加金额,当我再次点击同一行时我减去我添加的金额。我设法添加了它,但我不知道如何让它在再次单击时减去数量。

我已经设法使选定的行根据我是否选择它而改变颜色,但现在我需要在我再次单击该行时减去已添加的内容(如果我成功的话)。

这是我的 HTML:

            <tbody>
                <tr *ngFor="let item of articulos; index as i" (click)="total(item.cantidad)"
                    (click)="cambiarFlag(item)" 
                    [ngClass]="{'seleccionada': item.selected, 'noSeleccionada': !item.selected}">
                    <td>{{item.articulo}}</td>
                    <td>{{item.cantidad}}</td>
                    <td>{{item.recogida}}</td>
                </tr>
                <br>
            </tbody>

        <div type="button" class="col border border-white border-4" id="other" type="button"
            routerLink="/entry-order-lines-quantity" style="background-color:rgb(3, 71, 150);">
            Cantidad {{totalCantidad}}
        </div>

这是我的 ts:

export class EntryOrderLinesComponent implements OnInit {
  totalCantidad: number = 0;

  articulos = [
    {
      articulo: '385/65X22.5 HANKOOK AH51 160K (3003836)',
      cantidad: 94,
      recogida: '0',
      selected: false,
    },
    {
      articulo: '385/65X22.5 HANKOOK TH31 164K (3003309)',
      cantidad: 60,
      recogida: '0',
      selected: false,
    },
  ];

  total(cantidad: number) {
    this.totalCantidad += cantidad;
  }

  cambiarFlag(item: any) {
    item.selected = !item.selected;
  }

非常感谢你。

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    当我们需要执行两个函数时,我们应该使用一个唯一的“事件”并用“;”分隔。功能。有些喜欢:

     <tr *ngFor="let item of articulos; index as i" 
        (click)="total(item.cantidad);cambiarFlag(item)">
    

    好吧,如果总是一样,我们可以使用一个独特的功能

     <tr *ngFor="let item of articulos; index as i" 
        (click)="selectAndCalculateTotal(item)">
    

    并使用

    selectAndCalculateTotal(item:any)
    {
        item.selected=!item.selected;
        this.totalCantidad+=(item.selected)?-item.cantidad:item.cantidad;
    }
    

    实际上,如果您有几个元素(少于 50 或 100),最好使用数组项而不是使用辅助变量来计算总数。这是最差的性能,但更“健壮”。所以你可以使用吸气剂

    get total()
    {
       return this.items.reduce((a:number,b:any)=>{
         return b.selected?a+b.cantidad:a
       },0))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-07
      • 2023-01-17
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      相关资源
      最近更新 更多