繁体   English   中英

如何在 Angular 8 的嵌套对象数组中存储值

[英]How can I store value in a nested object array in Angular 8

我正在创建一个订单输入表单,我们将在其中存储主数据和详细数据。 下面我将向您展示我用打字稿写的实体详细信息。

 export interface IOrder {   
       id: number;   
       customerId: number;  
       orderDate: Date;   
       orderAmount: number;   
       orderDiscount: number; 
       finalAmount: number;   
       status: string;   
       orderDetail: IOrderDetail[];
    }
    export interface IOrderDetail {
        id: number;  
        serviceName: string;
        serviceDescription: string;
        quantity: number;
        price: number;
        discount: number;
        amountAfterDiscount: number;
     }

以下是我的表格截图:

在此处输入图片说明

单击加号 (+) 后,它会将订单项添加到网格中。 下面提到的功能将完成这项工作。

addToGrid() {
this.itemCount=(this.order.orderDetail.length);  
this.order.orderDetail[this.itemCount].id = 0;
this.order.orderDetail[this.itemCount].serviceDescription = this.serviceDescription.value;
this.order.orderDetail[this.itemCount].serviceName = this.serviceName.value;
this.order.orderDetail[this.itemCount].price = this.price.value;
this.order.orderDetail[this.itemCount].quantity = this.quantity.value;
this.order.orderDetail[this.itemCount].discount = this.discount.value;
this.order.orderDetail[this.itemCount].amountAfterDiscount = ((this.quantity.value * this.price.value) - this.discount.value);
console.log(this.order.orderDetail);
}

我收到 orderDetail 未定义错误。 请帮我缩短我的问题。

下面是我的 Component.ts 文件:

  export class AddorderComponent implements OnInit {
      dbops = DBOperation.create;
      orderForm: FormGroup;
      itemList: IServiceOffer[];
      custList: ICustomer[];
      id: number;
      order: IOrder;
      errorMessage: any;
      title: string;  
      itemCount: number;

   constructor(private _fb: FormBuilder, private calendar: NgbCalendar,
private _avRoute: ActivatedRoute,
private _orderService: OrderService,
private _router: Router) {
if (this._avRoute.snapshot.params["id"]) {
  this.id = this._avRoute.snapshot.params["id"];
}
this.orderForm = this._fb.group({
  id: ['', [Validators.required]],
  customerId: ['', [Validators.required]],      
  orderDate: ['', [Validators.required]],
  orderAmount: [ '' , [Validators.required]],
  orderDiscount: [''],
  finalAmount: [''],
  status: [''],
  serviceId: [''],
  serviceName: ['', [Validators.required]],
  serviceDescription: ['',[Validators.required]],
  price: [''],
  quantity: ['',[Validators.required, Validators.pattern("^[0-9]*$")]],
  discount: [ '', [Validators.pattern("^[0-9]*$")]],
  amountAfterDiscount: [''] 
  });
}
 ngOnInit() {
   this.getCustomerList();
   this.getServiceList();
   if (this.id > 0) {
    this.editOrder(this.id);
    // console.log(this.customer);
    } else {
     this.addOrder();
   }
  }

saveOrder() {
 this.order = this.orderForm.value;
  if (!this.orderForm.valid) {
  return;
}
if (this.dbops == DBOperation.create) {
  console.log(this.order);

  this._orderService
    .saveOrder(Global.BASE_API_ENDPOINT + "order/add", this.order)
    .subscribe(
      () => {
        this._router.navigate(["order"]);
      },
      error => (this.errorMessage = error)
    );
  } else if (this.dbops == DBOperation.update) {
    this._orderService
    .updateOrder(
      Global.BASE_API_ENDPOINT + "order/update",
      this.order
    )
    .subscribe(
      () => {
        this._router.navigate(["order"]);
      },
      error => (this.errorMessage = error)
    );
  }
 }
 cancel() {
    this._router.navigate(["order"]);
  }
 addOrder() {
    this.dbops = DBOperation.create;
    this.title = "Add New Order";
  }

editOrder(id: number) {
   this.dbops = DBOperation.update;
   this.title = "Edit Order";
   this._orderService
     .getOrderById(Global.BASE_API_ENDPOINT + "order/details", id)
     .subscribe(data => this.orderForm.setValue(data));
  }
 getCustomerList() {
    this._orderService
    .getCustomerList(Global.BASE_API_ENDPOINT + "customer/allcustomer")
    .subscribe(data => (this.custList = data));
}
 getServiceList() {
    this._orderService
   .getServiceList(Global.BASE_API_ENDPOINT + "serviceoffer/allservice")
   .subscribe(data => (this.itemList = data));
 }

addToGrid() {
   this.itemCount=(this.order.orderDetail.length);  
   this.order.orderDetail[this.itemCount].id = 0;
   this.order.orderDetail[this.itemCount].serviceDescription 
        = this.serviceDescription.value;
   this.order.orderDetail[this.itemCount].serviceName 
        = this.serviceName.value;
   this.order.orderDetail[this.itemCount].price = this.price.value;
   this.order.orderDetail[this.itemCount].quantity = this.quantity.value;
   this.order.orderDetail[this.itemCount].discount = this.discount.value;
   this.order.orderDetail[this.itemCount].amountAfterDiscount 
       = ((this.quantity.value * this.price.value) - this.discount.value);

        console.log(this.order.orderDetail);
   }

   getServicedetails(value: any) {    
      this._orderService
     .getServiceDetails
          (Global.BASE_API_ENDPOINT + "serviceoffer/details", value)
     .subscribe(data => ( 
       this.serviceDescription.setValue(data.serviceDescription),
        this.serviceName.setValue(data.serviceName),
       this.price.setValue(data.servicePrice)
   ));
 }

 get customerId() {
    return this.orderForm.get("customerId");
 }
 get serviceId() {
    return this.orderForm.get("serviceId");
 }
get serviceName() {
   return this.orderForm.get("serviceName");
}
get serviceDescription() {
   return this.orderForm.get("serviceDescription");
}
get price() {
  return this.orderForm.get("price");
}
get quantity() {
   return this.orderForm.get("quantity");
}
get discount() {
   return this.orderForm.get("discount");
}
get orderDate() {
  return this.orderForm.get("orderDate");
}  
get orderAmount() {
  return this.orderForm.get("orderAmount");
}
get orderDiscount() {
   return this.orderForm.get("orderDiscount");
}
get finalAmount() {
   return this.orderForm.get("finalAmount");
}
get orderDetail() {
  return this.orderForm.get("order.orderDetail[]");
}
get status() {
   return this.orderForm.get("status");
 }

Shiv,问题是你没有初始化 orderDetail,但你有其他问题,你使用了一个陌生的 FormGroup。 按步骤:

创建两个返回 FormGroup 的函数

newOrderForm()
{
   return this._fb.group({
      id: ['', [Validators.required]],
      customerId: ['', [Validators.required]],      
      orderDate: ['', [Validators.required]],
      orderAmount: [ '' , [Validators.required]],
      orderDiscount: [''],
      finalAmount: [''],
      status: [''],
      orderDetail:this.fb.array([])
  })
}

newOrderDetailForm()
{
   return this._fb.group({
      serviceId: [''],
      serviceName: ['', [Validators.required]],
      serviceDescription: ['',[Validators.required]],
      price: [''],
      quantity: ['',[Validators.required, Validators.pattern("^[0-9]*$")]],
      discount: [ '', [Validators.pattern("^[0-9]*$")]],
      amountAfterDiscount: [''] 
  });
}

然后你使用这个函数创建你的表单,并有一个新的函数 getter 来管理 formArray

 this.orderForm=this.newOrderForm();

 get orderDetail()
 {
      return this.orderForm?this.orderForm.get('orderDetail') as FormArray:null
 }

现在是您可以编写 .html 的时候了

 <form [formGroup]="orderForm">
     <!---zone of main fields -->
     <input formControlName="customerId">
     <input formControlName="orderDate">
      .....
      <!--zone to manage the formArray--->
      <div formArrayName="orderDetail">
          <div *ngFor="let group of orderDetail.controls;let i=index"
                  [fromGroupName]="i">
               <!---inputs that belong to the array-->
                  <input formControlName="serviceId">
                  <input formControlName="serviceName">

          </div>
      </div>
 </form>

好了,现在回答您的问题,如何向 formArray 添加元素? 只需使用

addToGrid(){
   this.orderDetail.add(this.newOrderDetail())
}

看看这个Netanet Basal的帖子(这是我找到的最后一个,我认为它非常完整)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM