1
votes

Here is the mock data array i am looping over in my app.component.html

questions: [
{question: 'Question-1'},
{question: 'Question-2'},
{{question: 'Question-3'}
]

In my app.component.ts as follows, Since i am using reactive form approach i have instantiated the Form Group and declare a formControl named 'note' which is declared as required:

export class example {

regPresentationForm: FormGroup;

this.regPresentationForm = new FormGroup ({
   note: new FormControl(null, Validators.required),
});

}

In my component HTML i am looping over the array and displaying the text field, therefore will have three text boxes each with note as my formControl:

<ng-container *ngFor = "let question of questions">
  <textarea type="text" id="textArea" placeholder="Enter the Note" class="form-control" formControlName = "note">
  </textarea>
</ng-container>

Since the note formcontrol is required i am disabling the submit button like this:

<button class="btn btn-primary" type="submit"[disabled] =  "!regPresentationForm.valid">
  Save & Continue
</button>

PROBLEM:

The problem is the form get valid if i enter a text on the first text box therefore angular is considering it as a single box repeated thrice, which should not happen it should consider each note field seperately (3 instance of note formcontrol since the iteration is done thrice)

No idea how to figure this out need helps.

I hope i am clear.

1

1 Answers

0
votes

You can loop formControl like this : On ts side:

 form2: FormGroup;
 testData:any;
 formDataInfo: any;


  constructor() {  }

 ngOnInit() {
    this.testData = [];
    this.formDataInfo = {}; 

   for(var i=0; i<2; i++){
    var currentNote = 'note' + i;

    this.formDataInfo[currentNote] = new FormControl(null, 
    Validators.required);

    this.testData.push({ "value": currentNote, "key": "firstName1", 
      "label": "First name",
      "required": true, "order": 1, "controlType": "textbox", 
      "type": "text" 
    }); 

  }
  this.form2 = new FormGroup (
    this.formDataInfo
  );
}

On HTML side:

<div [formGroup]="form2">
  <ng-container *ngFor="let question of testData" class="form-row">
    {{question | json}} {{question.key}}
        <textarea type="text" placeholder="Enter the Note"    
          class="form-control" [formControlName]="question.value" 
          [required]="question.required"> 
        </textarea> 
    </ng-container>
</div>