Можно ли обновить значение ключа объекта, повторенного с помощью ngFor в Angular 6 - PullRequest
0 голосов
/ 07 апреля 2020

Используя ответ API, созданные dom-элементы, используя ngFor, следующим образом.

HTML

 <div class="col-sm-2 p-1 eventDiv ripple-container" *ngFor="let actProd of actProdList;let i = index">
    <mat-card  matRipple class="p-0">
        <div class="d-flex justify-content-center mt-2">
        <div class="w-100 ProductPrice d-flex justify-content-center">{{actProd?.PRICE}}<span class="pl-1" [innerHtml]="mCurrencyCode"></span></div>

        <button type="button" (click)="decrement(actProd?.CODE,i)" class="btnStyles">–</button>
        <input type="text" #TotalCartCount readonly class="quantityBox" value="{{mItemCount}}">
        <button type="button" (click)="increment(actProd?.CODE,i)" class="btnStyles">+</button>
        </div>
    </mat-card>
</div>

Машинопись

increment(ItemId:number,index:number) {
    this.mItemCount += 1;
  }

Что я хочу сделать, когда пользователь нажимает кнопку «+», мне нужно обновить цену. Как этого добиться, не обновляя дом.

1 Ответ

0 голосов
/ 08 апреля 2020

В вашем случае вам лучше создать два новых свойства. Один для количества продукта и один для общей цены, которая изменяется в зависимости от количества. Попробуйте следующий

Контроллер

export class AppComponent  {
  name = 'Angular';
  mItemCount = 1;
  actProdList = [
    { 'CODE': 1, 'PRICE': 25 },
    { 'CODE': 2, 'PRICE': 99 },
    { 'CODE': 3, 'PRICE': 100 },
    { 'CODE': 4, 'PRICE': 300 },
    { 'CODE': 5, 'PRICE': 12 }
  ];
  mCurrencyCode = '&#36;';

  constructor() {
    this.actProdList.forEach(product => {     // <- create new properties here
      product['quantity'] = 0;
      product['totalPrice'] = 0;
    });
  }

  increment(ItemId: number, index: number) {
    this.actProdList[index]['quantity'] += 1;
    this.actProdList[index]['totalPrice'] = this.actProdList[index]['PRICE'] * this.actProdList[index]['quantity'];
  }

  decrement(ItemId: number, index: number) {
    this.actProdList[index]['quantity'] -= 1;
    this.actProdList[index]['totalPrice'] = this.actProdList[index]['PRICE'] * this.actProdList[index]['quantity'];
  }
}

Шаблон

<div class="col-sm-2 p-1 eventDiv ripple-container" *ngFor="let actProd of actProdList;let i = index">
  <div class="d-flex justify-content-center mt-2">
    <div class="w-100 ProductPrice d-flex justify-content-center">{{actProd?.totalPrice}} <span class="pl-1" [innerHtml]="mCurrencyCode"></span></div>

    <button type="button" (click)="decrement(actProd?.CODE,i)" class="btnStyles">–</button>
    <input type="text" #TotalCartCount readonly class="quantityBox" value="{{actProd?.quantity}}">
    <button type="button" (click)="increment(actProd?.CODE,i)" class="btnStyles">+</button>
  </div>
</div>

Рабочий пример: Stackblitz

...