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?

5
  • 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 Commented Oct 21, 2017 at 4:59
  • Thanks for ur reply.I update my code.Kinldy check it. Commented Oct 21, 2017 at 5:02
  • When working with FormArray you should use index to access to control. Commented Oct 21, 2017 at 5:03
  • 1
    Look how it should be stackblitz.com/edit/… This answer may also help you to work with FormArray in the right way stackoverflow.com/questions/42783400/… Commented Oct 21, 2017 at 5:08
  • @yurzui.Thank u so much.It's work. Commented Oct 21, 2017 at 5:11

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.