I am working on billing of product page based on product list using Angular as front end. Component view

在这里,当我 Select 产品"苹果"时,价格应该被计算并显示在价格控制输入中. 也就是说.价格=产品价格*数量 例如,10*1=10 下面是我的组件html代码

<form [formGroup]="productFormarray" (ngSubmit)="onSubmit()">
          <div class="reg-right">
            <div class="formGroup">
              <label for="customername" class="form-label">Customer Name</label>
              <input type="text" class="form-control" id="customername" placeholder="Customer Name"
                formControlName="customername">
            </div>
            <div class="formGroup" formArrayName="productdetails">
              <div class="table-responsive">
                <table class="table table-bordered">
                  
                  <thead>
                    <tr>  <td style="width:50%">
                      Product Name
                    </td>
                    <td style="width:15%">
                      Quantity
                    </td>
                    <td style="width:20%">
                      Price
                    </td></tr>
                    </thead>
                  <tr *ngFor="let product of productdetailsarray.controls; let i=index" [formGroupName]="i">
                   
                    <td style="width:50%">
                      <div class="formGroup">
                          <select class="form-control" id="productname" formControlName="productname" name="productname" placeholder="Product Name">
                            <option disabled>select product</option>
                            <option *ngFor="let product of productlist" [ngValue]="product.productname">
                              {{product.productname}}
                            </option>
                          </select>
  
                        </div>
                    </td>
                    <td  style="width:15%">
                      <div class="formGroup">
                        <select class="form-control" id="quantit" formControlName="quantit" name="quantit">
                          <option *ngFor="let quantity of quantitylist" [ngValue]="quantity">
                            {{quantity}}
                          </option>
                        </select>
                      </div>
                    </td>
                    <td style="width:20%">
                      <div class="formGroup">
                        <input type="text" class="form-control" id="price" formControlName="price" placeholder="Price "
                          name="price" [value]="'33'">
                      </div>
                    </td>
                    <td>
                      <a type="button" class="btn btn-primary btn-sm mt-4" style="background-color: red;"
                      (click)="removeProduct(i)">Remove (-)</a>
                      </td>
                      
                    </tr>
                </table>
              </div>
              <a type="button" class="btn btn-secondary" style="background-color: green;"
              (click)="addNewProduct()">Add(+)</a>
                <br/>
           </div>
           <div class="mb-4 mt-4 col-md-12">
            <div class="formGroup">
              <label class="form-check-label">
                <input class="form-check-input" formControlName="remember" type="checkbox" name="remember"> Remember
                me
              </label>
            </div>
          </div>
           <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </form>

在我的组件打字代码下面

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormControl, FormArray, FormBuilder, NgForm, Validators } from '@angular/forms'
import { Observable, of } from 'rxjs';
import { toArray } from 'rxjs';


@Component({
  selector: 'app-billing',
  templateUrl: './billing.component.html',
  styleUrls: ['./billing.component.css']
})


export class BillingComponent implements OnInit {

  name = 'Bill';
  productsForm!: NgForm;
  @ViewChild('productsForm') productsForminput!: NgForm;

  productFormarray: any;
  quantitylist = [0.5, 1, 1.5];
  items!: FormArray;
  ind: number = 0;
  i: number = 0;
  productlist = [{ productname: "apple", price: 10 }, { productname: "orange", price: 10 }, { productname: "lemon", price: 30 }];

  constructor(private fb: FormBuilder) {
    this.productFormarray = new FormGroup({
      customername: new FormControl('', Validators.required),
      productdetails: new FormArray([]),
      remember: new FormControl('true')
    })

  }

  addNewProduct() {
    this.items = this.productFormarray.get('productdetails') as FormArray;
    this.items.push(this.createNewProduct());
    this.productFormarray.get('productdetails').controls[this.ind].get('quantit').setValue(this.quantitylist[1]);
    this.ind = this.ind + 1;
  }

  createNewProduct(): FormGroup {
    return new FormGroup({
      productname: new FormControl('', Validators.required),
      quantit: new FormControl('1', Validators.required),
      price: new FormControl('', Validators.required)
    })
  }

  removeProduct(index: any) {
    this.items = this.productFormarray.get('productdetails') as FormArray;
    this.items.removeAt(index);

  }
  get productdetailsarray() {
    return this.productFormarray.get('productdetails') as FormArray;
  }

  ngOnInit() {
    this.addNewProduct();

  }


  onSubmit() {

  }


}

有没有人能帮我弄清楚价格价值?

推荐答案

您可以通过获得productquintity的值并将其监听到addNewProduct中来实现这一点

  onProductChange(selectedProductName: string, index: number) {
    const selectedProduct = this.productlist.find(
      (product) => product.productname === selectedProductName
    );
    if (selectedProduct) {
      const productDetailsArray = this.productFormarray.get(
        'productdetails'
      ) as FormArray;
      if (productDetailsArray && productDetailsArray.at(index)) {
        const quantityControl = productDetailsArray.at(index).get('quantit');
        if (quantityControl) {
          // Reset the quantity to its default value
          quantityControl.setValue(this.quantitylist[1], { emitEvent: false });

          const quantity = quantityControl.value;
          const price = selectedProduct.price * quantity;
          const priceControl = productDetailsArray.at(index).get('price');
          if (priceControl) {
            priceControl.setValue(price);
          }
        }
      }
    }
  }

  onQuantityChange(selectedQuantity: number, index: number) {
    const productDetailsArray = this.productFormarray.get(
      'productdetails'
    ) as FormArray;
    if (productDetailsArray && productDetailsArray.at(index)) {
      const productNameControl = productDetailsArray
        .at(index)
        .get('productname');
      if (productNameControl) {
        const selectedProductName = productNameControl.value;
        const selectedProduct = this.productlist.find(
          (product) => product.productname === selectedProductName
        );
        if (selectedProduct) {
          const price = selectedProduct.price * selectedQuantity;
          const priceControl = productDetailsArray.at(index).get('price');
          if (priceControl) {
            priceControl.setValue(price);
          }
        }
      }
    }
  }

  addNewProduct() {
    this.items = this.productFormarray.get('productdetails') as FormArray;
    const newProduct = this.createNewProduct();
    this.items.push(newProduct);

    const index = this.items.length - 1;

    newProduct.get('quantit')?.setValue(this.quantitylist[1]);

    const productNameControl = newProduct.get('productname');
    if (productNameControl) {
      productNameControl.valueChanges.subscribe((selectedProductName) =>
        this.onProductChange(selectedProductName, index)
      );
    }

    const quantityControl = newProduct.get('quantit');
    if (quantityControl) {
      quantityControl.valueChanges.subscribe((selectedQuantity) =>
        this.onQuantityChange(selectedQuantity, index)
      );
    }
  }

这是工作示例 [Stackblitz]

Angular相关问答推荐

如何以条件为值管理ngIf内部的未定义值?

HTTP Get请求未发送到提供的URL

FormArray包含嵌套的FormGroups.如何访问嵌套的表单组控件?

布局之间的Angular 变化检测需要重新加载

Angular 单元测试组件s @ Input.'变化值检测

Angular 15:将数据从主零部件传递到辅零部件

以Angular 动态添加和删除组件形状元素

在Drective Composure API中使用指令输出

角路径S异步旋转变压器仍可观察到

Angular 单位测试表

显示用户名-Angular

具有两个订阅方法的 Angular 16 takeUntilDestroyed 运算符

Angular/RxJS 6:如何防止重复的 HTTP 请求?

错误:您要查找的资源已被删除、名称已更改或暂时不可用

如何从Angular 2 中的按钮单击触发输入文件的单击事件?

Angular 5 手动导入语言环境

默认情况下如何在Angular中 Select mat-button-toggle

错误:angular2 中没有 HttpHandler 的提供者

在 Angular 组件模板中添加脚本标签

缺少带有Angular的语言环境XXX的语言环境数据