Невозможно передать индекс из массива внешней формы во внутренний formArray в угловой реактивной форме - PullRequest
0 голосов
/ 21 февраля 2019

Я пытаюсь передать индекс внешнего массива во внутренний массив формы, но массив внутренней формы находится в модальном окне, поэтому я не могу передать значение индекса ..

HTML-код:

<code><div class="page-head">
  <h3>Add New GRN</h3>
  <ol class="breadcrumb">
    <li class=""><a routerLink="/store-homepage">Home</a></li>
    <li class="active">Enter GRN#</li>
  </ol>
</div>
<div class="cl-mcont">
  <div id="loaderID" style="position:fixed; top:50%; left:50%; z-index:2; opacity:0"><img
      src="assets/images/ajax-loading-img.gif" /></div>
  <div class="row" id="grnContainer">
    <div class="col-sm-12">
      <div class="block-flat">
        <div class="content">
          <form class="form-horizontal" id="grnFrm" [formGroup]="grnDetails"
          role="form" action="GrnView.php" parsley-validate novalidate
            method="post">
            <input type="hidden" name="store_id" value="">
            <div class="form-group">
              <label for="po_number" class="col-sm-3 control-label">PO No</label>
              <div class="col-sm-6">
                <input type="text" required class="form-control" #po id="poName" 
                maxlength="25" formControlName="po_number"
                  (keyup)="autoCompletePo(po.value)" (change)="fetchPo(po.value)" 
                  placeholder="PO No" list="po_ids">
                <datalist id="po_ids">
                  <option *ngFor="let po of filtered_po_list">{{po.po}}</option>
                </datalist>
              </div>
            </div>
            <div class="form-group">
              <label for="grn" class="col-sm-3 control-label">GRN No</label>
              <div class="col-sm-6">
                <input type="text" required class="form-control" id="grn" #grn
                maxlength="25" placeholder="G R N" name="grn" formControlName="grn_number"                  
                value="" (keyup)="checkGrn(grn.value)">
                <input type="hidden" name="grnExist" id="grnExist" value="">
                <label class="error_txt" id="grn_exist_error"></label>
                <label class="error_txt" id="grn_exist_error" *ngIf="grn_flag">
                  A GRN Already exist with the same GRN Num</label>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label" for="in_time"> In Time </label>
              <div class="col-sm-2">
                <input class="form-control" size="16" type="date" class="date1" 
                placeholder="Entry Date" value="" (change)="getTime(time.value)" #time
                  name="in_time" id="grnDate" required formControlName="grn_time">
              </div>

            </div>
            <div class="control-group">
              <div class="controls">
                <div class="table-responsive">
                  <table class="table table-bordered">
                    <thead>
                      <tr>
                        <th><input type="checkbox" name="chkAllComp" id="chkAllComp"></th>
                        <th>Part Number</th>
                        <th>Part Description</th>
                        <th>Ordered Qty</th>
                        <th>Recieved</th>
                        <th>Expiration Date </th>
                        <th>Unit Cost (INR)</th>
                        <th>Grn Qty</th>
                        <th>Actions</th>
                      </tr>
                    </thead>
                    <tbody id="components_tbl" formArrayName="components">
                      <tr class="item_row" id="checkbox"
                      *ngFor="let poOrder of grnDetails['controls'].components['controls'] ; let i=index" [formGroupName]="i"> 
                        <td><input type="checkbox" name="componentRow[]" 
                          class="componentRow" #check (change)="onChanges(i)"
                          value="" formControlName="selected">{{i}}</td>
                        <td><input type="hidden" class="componentId" name="componentId[1]" value="">
                          <input type="hidden" value="" formContorlName="part_no"
                            value="H-24" name="componentName[1]" class="form-control componentName">
                            {{poOrder.controls.part_no.value}}
                        </td>
                        <td><input type="hidden" value="" 
                          name="partDescription[1]" 
                            class="form-control partDescription">{{poOrder.controls.description.value}}</td>
                        <td><input type="hidden" class="orderedQty" name="ordered_quantity" readonly
                          value="" formControlName="ordered_quantity">{{poOrder.controls.ordered_quantity.value}}</td>
                        <td><input type="hidden" class="receivedTotQty" name="received_quantity" 
                            value="" formControlName = "received_quantity">{{poOrder.controls.received_quantity.value}}</td>
                        <td><input type="hidden" class="expDate expDate1" name="exp_date[1]" 
                          value="" formControlName="exp_date">{{poOrder.controls.exp_date.value}}</td>
                        <td><input type="text" placeholder="Price"
                            class="form-control col-sm-6 only-numbers productPrice" 
                            value="" formControlName="unit_price"
                            name="productPrice[1]"></td>
                        <td><input type="hidden" name="grnQty[1]" class="grnQty"><span class="grnQtyLabel"></span></td>
                        <td><button type="button" class="btn btn-warning" data-toggle="modal" 
                          data-target="#locaBox1" (click)="modalClicked(i,poOrder)" [disabled]="!check.checked">
                            <i class="fa fa-globe"></i>Add Locations</button>
                          <div aria-hidden="true" style="display: none;" class="modal fade" id="locaBox1"
                            role="dialog">
                            <div class="modal-dialog">
                              <div class="modal-content">
                                <div class="modal-header"><button type="button" class="close" data-dismiss="modal"
                                    aria-hidden="true">×</button></div>
                                <div class="modal-body">
                                  <div class="suppliersBlock">
                                    <div class="header">
                                      <h4>Add Location List</h4>
                                    </div>
                                    <table class="table table-bordered" formArrayName="assigned_locations">
                                      <tbody id="locations_tbl1" *ngFor="let location_control of poOrder.controls.assigned_locations.controls ; let j=index"
                                      [formGroupName]="j">
                                        <tr>
                                          <th>Store</th>
                                          <th>Location</th>
                                          <th>Quantity</th>
                                          <th></th>
                                        </tr>
                                        <tr id="1rowWas1" class="loc_row">
                                          <td><select name="storeName1[]" (change)="getLocation(store.value)" #store
                                              class="form-control storedropdown_id storeName1" formControlName="store"
                                              id="{{storeNameId+j}}">
                                              <option value="">Select Store {{mainLoopI}}</option>
                                              <option value="{{store.storeId}}" *ngFor="let store of store_list">{{store.name}}</option>
                                            </select><input type="hidden" name="storeSelectedLabel1[]" 
                                              class="storeSelectedLabel storeSelectedLabel1" value=""></td>
                                          <td><select id="locationid" name="location_id1[]" formControlName="location"
                                              class="form-control locationName_id location_id1">
                                              <option value="">Select Location</option>
                                              <option value="{{location.location_id}}" *ngFor="let location of location">
                                                {{location.location}}</option>
                                            </select><input type="hidden" name="locationSelectedLabel1[]" 
                                              class="locationSelectedLabel locationSelectedLabel1" value=""></td>
                                          <td><input type="text" placeholder="Quantity" formControlName="quantity"
                                              class="form-control col-sm-6 only-numbers locationQty locQty1"
                                              name="quantity1[]" id="quantity"></td>
                                          <td></td>
                                        </tr>
                                      </tbody>
                                      <tbody>
                                        <tr class="addLocBtnRow">
                                          <td><input type="hidden" class="tablerow" name="tablerow[]" value="1"> </td>
                                          <td></td>
                                          <td><button type="button" class="btn btn-info add_new_locations"
                                              id="add_new_locations" (click)="addMoreLocation()"><i class="fa fa-plus"></i>Add
                                              Locations</button></td>
                                          <td></td>
                                        </tr>
                                      </tbody>
                                    </table>
                                  </div>
                                </div>
                                <div class="modal-footer"><button type="button" class="btn btn-success" (click)="locationSubmit()"
                                    data-dismiss="modal" ><i class="fa fa-check"></i> Submit</button><button
                                    type="button" class="btn btn-danger" data-dismiss="modal" ><i
                                      class="fa fa-times"></i> Cancel</button></div>
                              </div>
                            </div>
                          </div>
                        </td>
                      </tr>
                    </tbody>

                  </table>
                </div>
              </div>
            </div>
            <div class="form-group">
              <div class="col-sm-12">
                <div class="col-sm-9" id="grnErrMsg"></div>
                <div class="col-sm-3">
                  <button class="btn btn-primary" type="button" name="submitStore" id="submitStore"><i
                      class="fa fa-check"></i> Submit</button>
                  <a class="btn btn-danger"><i class="fa fa-times"></i>Cancel</a>
                </div>
              </div>
            </div>
          </form>
          <h5>Field Values</h5>
    <pre style="font-size:15px">{{ grnDetails.value | json }}

FormGroupObject:

{
  "po_id": 398,
  "po_number": "12345",
  "grn_number": "",
  "grn_time": "",
  "components": [
    {
      "part_no": "GS-ABF-029",
      "description": "ABF SCRUBBER BLOWER",
      "ordered_quantity": 89,
      "received_quantity": 80,
      "exp_date": "2019-10-17",
      "batch_id": 4639,
      "ordered_id": 893,
      "selected": null,
      "assigned_locations": [
        {
          "store": "",
          "location": "",
          "quantity": ""
        }
      ]
    },
    {
      "part_no": "VIMP-EEX-063",
      "description": "TMP POWER CABLE",
      "ordered_quantity": 20,
      "received_quantity": 1,
      "exp_date": "2019-08-17",
      "batch_id": 4640,
      "ordered_id": 895,
      "selected": null,
      "assigned_locations": [
        {
          "store": "",
          "location": "",
          "quantity": ""
        }
      ]
    }
  ]
}

в компоненте приложения iинициировал компонент FormArray со значениями, полученными с сервера, и оставил места как пустую инициализацию.но после размещения * ngFor во внешнем компонентном массиве этот индекс i не может пройти через локацию div, где location div - модальное окно, пожалуйста, помогите как это выяснить

app.component.ts:

import { LocationService } from './../../admin/location/location.service';
import { StoreService } from './../../admin/store/store.service';
import { PoOrder } from './po-order.model';
import { Po } from './po.model';
import { Component, OnInit } from '@angular/core';
import { StoresService } from '../stores.service';
import { Store } from 'src/app/admin/store/store.model';
import { FormBuilder, FormArray, FormGroup, FormControl, Validators } from '@angular/forms';
import { AssignLocation } from './assign-locations.model';

@Component({
  selector: 'app-enter-grn',
  templateUrl: './enter-grn.component.html',
  styleUrls: ['./enter-grn.component.css']
})
export class EnterGrnComponent implements OnInit {

  po_list: Po[] = [];
  filtered_po_list: Po[] = [];
  po_order_list: PoOrder[] = [];
  store_list: Store[] = [];
  location: any[] = [];
  grnDetails: FormGroup;
  po_number: string;
  po_id: number;
  grn_number: string;
  in_time: string;
  alloted_location: AssignLocation[] = [];
  available_grn: string[] = [];
  grn_flag: boolean = false;
  disabled: boolean = true;
  mainLoopI : number = 0;


  constructor(private _storesService: StoresService,
    private _storeService: StoreService,
    private _locationService: LocationService,
    private fb: FormBuilder) {
    this.getPo();
    this.getStore();
    this.getAvailableGrn();
  }
  ngOnInit() {
    this.grnArrayCreation();
  }

  getPo() {
    this._storesService.getPo()
      .subscribe(res => {
        this.po_list = res;
      }, (error) => {
        console.log(error.error.message);
      });
  }
  getStore() {
    this._storeService.getStores()
      .subscribe((res) => {
        this.store_list = res;
      }, (error) => {
        console.log(error.error.message);
      });
  }
  getAvailableGrn() {
    this._storesService.getGrnDetails()
      .subscribe(res => {
        this.available_grn = res;
      }, (error) => { console.log(error.error.message) })
  }

  autoCompletePo(search: string) {
    this.filtered_po_list = this.po_list.filter(v => v.po.toLowerCase().includes(search.toLowerCase()));
  }
  checkGrn(search: string) {
    var searchedGrn = this.available_grn.filter(v => v.toLowerCase() == (search.toLowerCase()))
    if (searchedGrn[0]) {
      this.grn_flag = true;
    }
    else {
      this.grn_flag = false;
      this.grn_number = search;
    }
  }
  getTime(time: string) {
    this.in_time = time;
  }
  grnArrayCreation() {
    this.grnDetails = this.fb.group({
      po_id: [''],
      po_number: [''],
      grn_number: [''],
      grn_time: [''],
      components: this.fb.array([])
    });
  }


  setComponents() {
    this.grnArrayCreation();
    this.grnDetails.patchValue({
      po_id: this.po_id,
      po_number: this.po_number
    });
    let control = <FormArray>this.grnDetails.controls.components;
    this.po_order_list.forEach(x => {
      control.push(this.fb.group({
        part_no: x.part_no,
        description: x.description,
        ordered_quantity: x.ordered_quantity,
        received_quantity: x.received_quantity,
        exp_date: x.exp_date,
        batch_id: x.batch_id,
        ordered_id: x.order_id,
        unit_price: [{ value: x.unit_cost_inr, disabled: true }],
        selected: x.selected,
        assigned_locations: new FormArray([
          this.addLocationsFormGroup()
        ])
      }))
    })
  }

  addLocationsFormGroup(): FormGroup {
    return this.fb.group({
      store: [''],
      location: [''],
      quantity: ['']
    })
  }

  deleteLocationsFormGroup(control, index) {
    control.removeAt(index);
  }

  addMoreLocation() {
    var control = (<FormArray>this.grnDetails.controls['components']).at(this.mainLoopI).get('assigned_locations') as FormArray
    control.push(this.addLocationsFormGroup());
  }

  fetchPo(po: string) {
    this.po_number = po;
    this.po_order_list = [];
    let poField = this.po_list.filter(v => v.po == po);
    this.po_id = poField[0].po_id;
    if (po) {
      this._storesService.fetchPoOrder(po)
        .subscribe((res) => {
          this.po_order_list = res;
          this.setComponents();
        }, (error) => {
          console.log(error.error.message);
        });
    }
  }
  getLocation(store: number) {
    this.location = [];
    this._locationService.getStoreLocation(store)
      .subscribe((res) => {
        this.location = res;
      }, (error) => {
        console.log(error.error.message);
      });
  }
  addedItems(batch_id: number) {
    console.log(batch_id);
  }
  submit(grnDetails) {

  }
  onChanges(i : number) {
    this.mainLoopI = i;
    var control = <FormArray>this.grnDetails.controls.components;
    if (this.grnDetails.controls.components.value[i].selected==true) {
      control.controls[i].get('unit_price').enable();
    }
    else {
      control.controls[i].get('unit_price').disable();
    }
  }
  locationSubmit(){
  }
  modalClicked(i,poOrder){
    this.mainLoopI = i;
  }
  selectStore(j,store){
    var control = (<FormArray>this.grnDetails.controls['components']).at(this.mainLoopI).get('assigned_locations') as FormArray
    control.at(j).patchValue({
      store : store
    });
  }
  selectLocation(j,location){
    var control = (<FormArray>this.grnDetails.controls['components']).at(this.mainLoopI).get('assigned_locations') as FormArray
    control.at(j).patchValue({
      location : location
    });
  }
}
...