elesh.j
elesh.j

Reputation: 344

Angular 4 Form Builder Array Add Validator

I am stuck on how to add validators: I am using Reactive Forms and I am creating a array using the Form Builder ( an array of an class). Here is the how I am creating the form, and setting the control for the array:

Creating Form:

createForm(): void{
 this.workOrderForm = this.fb.group({
  workOrderStatus: ['', Validators.required],
  completedDate: '',
  workOrderNotes : this.fb.array([]);
 });
}

Then after the form is creating, I call a method to add another control which is an array of type WorkOrderNote:

setNotes(notes: WorkOrderNote[]) {
 const noteFGs = notes.map(note => this.fb.group(note));
 const notesFormArray = this.fb.array(noteFGs);
 this.workOrderForm.setControl('workOrderNotes', notesFormArray);
}

WorkOrderNote has property called notes. I'd like to set a required validator on it. I am unable to find how an example on the Angular tutorials..

Upvotes: 2

Views: 1613

Answers (1)

Eliseo
Eliseo

Reputation: 57939

You have to work some with the "map" of setNotes. e.g. If your "note" have properties: field1 and field2, you can use

   const noteFGs = notes.map(note => {
      return this.fb.group(
         {
          field1:[note.field1],
          field2:[note.field2,Validators.required],
         })
    });

Upvotes: 2

Related Questions