简体   繁体   English

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

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

I am creating an order entry form where we shall store both master and details data.我正在创建一个订单输入表单,我们将在其中存储主数据和详细数据。 Below I am showing you my entity details which wrote in typescript.下面我将向您展示我用打字稿写的实体详细信息。

 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;
     }

Below is my Form Screenshot:以下是我的表格截图:

在此处输入图片说明

After clicking on the plus(+) sign it will add order item into the grid.单击加号 (+) 后,它会将订单项添加到网格中。 The below mention function will do that the job.下面提到的功能将完成这项工作。

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

I am getting orderDetail undefined error.我收到 orderDetail 未定义错误。 Please help me to short out my issue.请帮我缩短我的问题。

Below is my Component.ts file:下面是我的 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, the problem is that you has not initialize the orderDetail, but you has other problem, you are using a estrange FormGroup. Shiv,问题是你没有初始化 orderDetail,但你有其他问题,你使用了一个陌生的 FormGroup。 By steps:按步骤:

Create two functions that return a 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: [''] 
  });
}

Then you create your form using this functions and has a new function getter to manage the formArray然后你使用这个函数创建你的表单,并有一个新的函数 getter 来管理 formArray

 this.orderForm=this.newOrderForm();

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

Now is when you can write your .html现在是您可以编写 .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>

Well, now the response to your question, how add an element to the formArray?好了,现在回答您的问题,如何向 formArray 添加元素? Just use只需使用

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

Take a look to this Netanet Basal's Post (it's the last I found, and I think that it's very complet)看看这个Netanet Basal的帖子(这是我找到的最后一个,我认为它非常完整)

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

相关问题 如何根据 Angular 8 中的嵌套 object 值过滤 object 数组 - How to filter array of object based on nested object value in Angular 8 如何以角度具有字段值的形式返回嵌套对象数组的特定字段? - How do I return specific field of nested object array in angular having fields value? 如何将 FormArray 中的单独数据存储到 Angular 中的普通 object 数组中 - How can i store separate data from an FormArray into an normal object array in Angular 如何在Angular中使用ngFor获取嵌套对象数组的选定值? - How to get selected value of nested object array using ngFor in Angular? Angular - 如何将 Object 转换为数组 - Angular - How can i transform an Object into an Array 如何使用 Angular 更改对象值 - How can I change object value with Angular 我怎样才能将对象存储在本地存储中的角度? - How can i store object in local storage in angular? 如何访问 Angular 中嵌套的 object 的属性? - How can I access the properties of a nested object in Angular? 如何使用给定的属性值计算数组中的对象 (Angular-FirebaseRealtime) - How Can I Count Object's in Array With Given Property Value (Angular-FirebaseRealtime) 如何将具有较低价格字段值的数组对象直接选择到此 Angular 应用程序的 HTML 中? - How can I select the array object having the lower price field value directly into the HTML of this Angular application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM