1

I have seen examples and I have not been able to find a way to validate my form. I basically have a form that consists of an array of fields that I want to validate because they are required.

this.formNames = this.fb.group({
  element_name: new FormControl('', [Validators.required]) //input text 
});

this.myForm = this.fb.group({
  names: this.fb.array([
      this.formNames,  
      this.formNames
  ])
})

enter image description here

I have the problem that I am trying to validate the text fields that are represented by: names and are required. but what happens in the image happens if I add text in any text field, they are all validated, I want that when I write something in the corresponding text field, validation is done exclusively for that field.

this is my live code:

https://stackblitz.com/edit/angular-xkhkoc?file=app/app.component.ts

<form [formGroup]="myForm">
  <div formArrayName="names">
  <ng-container
      *ngFor="let item of myForm.get('names').controls; let i=index">
      <div [formGroupName]="i">
              <input type="text" class="form-control" id="element_name"
                  formControlName="element_name"
                  placeholder="insert name" 
              >
              {{item.controls['element_name'].valid | json}}
      </div>
   </ng-container>
  </div>
 </form>

1 Answer 1

1

You are using the same object to all inputs. Try this.

this.myForm = this.fb.group({
  names: this.fb.array([
    this.fb.group({ element_name: [null, [Validators.required]] }),
    this.fb.group({ element_name: [null, [Validators.required]] }),
  ])
})
Sign up to request clarification or add additional context in comments.

2 Comments

Currently this solution not works with my code, can you help me please?
can you help me with this please: stackoverflow.com/questions/57932590/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.