2

I am using angular 2. I need validation form reactive form with formArray.

Here is my form.

this.addbookingForm = this.fb.group({
      FROM: ['', Validators.required],
      ITEMS: this.fb.array([this.initItems()]),

})

 initItems() {        
    const group = this.fb.group({           
          NAME: [''],
          NO_OF_ITEMS: ['',Validators.required],
          PRICE: [''],
          WEIGHT: [''],
          TOTAL: ['']                     
    });
    return group;
}

Here is my form.

<form [formGroup]="addbookingForm" role="form" (ngSubmit)="onSubmit(addbookingForm.value)"  novalidate>

    <div formArrayName="ITEMS" class="form-group row">
         <div class="form-group col-sm-2">
                <label class="form-label">No of Items</label>
                <input type="text" pattern="^[0-9]*$" class="form-control" tabindex="7" formControlName="NO_OF_ITEMS" (change)="onChange(ITEMS.controls.value.NO_OF_ITEMS)">
                <p class="err" danger padding-left *ngIf="(!addbookingForm.controls.ITEMS.controls.NO_OF_ITEMS.valid)">Invalid number of items</p>
        </div>
    </div> 
</form>

But i am getting this error message

ERROR TypeError: Cannot read property 'valid' of undefined

How can i fix this issue?

James Z
  • 12,209
  • 10
  • 24
  • 44
vaishuani
  • 131
  • 1
  • 4
  • 13
  • What is the `in` in `ITEMS.controls[in]`? This template throws the error `Cannot find control with path: 'ITEMS -> NO_OF_ITEMS'` Please post correct code – yurzui Oct 21 '17 at 04:59
  • Thanks for ur reply.I update my code.Kinldy check it. – vaishuani Oct 21 '17 at 05:02
  • When working with FormArray you should use index to access to control. – yurzui Oct 21 '17 at 05:03
  • 1
    Look how it should be https://stackblitz.com/edit/angular-gtnqke?file=app%2Fapp.component.html This answer may also help you to work with FormArray in the right way https://stackoverflow.com/questions/42783400/nested-arrays-in-angular-2-reactive-forms/42904372#42904372 – yurzui Oct 21 '17 at 05:08
  • @yurzui.Thank u so much.It's work. – vaishuani Oct 21 '17 at 05:11

1 Answers1

0

change your code like below

<p class="err" danger padding-left 
    *ngIf="(!addbookingForm.controls.ITEMS.controls[0].controls.NO_OF_ITEMS.valid)">
Invalid number of items</p>
Michal
  • 2,078
  • 23
  • 36
Dharan
  • 262
  • 2
  • 14
  • You can improve your answer by editing it and adding explanation on how your suggestion works - how it solves the problem stated in the question. – Michal Nov 28 '18 at 10:27