energichen
energichen

Reputation: 26

ERROR Error: Cannot find control with name:

I'm trying to submit reactive form with form arrays, I've tried solutions from other threads but none worked for me, I feel like I'm missing something. Exact errors are ERROR Error: Cannot find control with name: 'stepName' and ERROR Error: Cannot find control with name: 'stepDesc'. Here is a sample code: Html:

<div formArrayName="knowSteps" cdkDrag *ngFor="let formGroup of knowSteps.controls; let i = index">
            <div [formGroup]="knowSteps.controls[i]">
              <mat-accordion>
                <mat-expansion-panel class="step-expand">
                  <mat-expansion-panel-header cdkDragHandle class="drag-drop">
                    <p>{{steptitle.value == '' ? 'Step' : steptitle.value}}</p>
                  </mat-expansion-panel-header>
                  <div clas="row">
                    <div class="col-md-12  p-3 mb-2 step-name" >
                      <mat-form-field appearance="outline">
                        <mat-label>Step Name</mat-label>
                        <input matInput formControlName="stepName" name="stepName" #steptitle>
                      </mat-form-field>
                    </div>
                  </div>
                  <div clas="row">
                    <div class="col-md-12  p-3 mb-2 step-description">
                      <mat-form-field appearance="outline">
                        <mat-label>Step Description</mat-label>
                        <textarea matInput formControlName="stepDesc" name="stepDesc"></textarea>
                      </mat-form-field>
                    </div>
                  </div>

Please ignore the not closed divs from the form.

  ngOnInit() {
    this.knowhowForm = this.formBuilder.group({
    knowSteps: this.formBuilder.array(
     [[this.knowledgeStepsForm()]],
  )
});

  knowledgeStepsForm() {
    return this.formBuilder.group({
    stepName: new FormControl('', [Validators.required]),
    stepDesc: new FormControl('', [Validators.required]),
  })
}

 get knowSteps(): FormArray {
   return this.knowhowForm.get('knowSteps') as FormArray;
 }

My submit form:

createKnowledge(){
   this.newKnowledge.knowledge_steps = this.knowhowForm.get('knowSteps').value;
}

I've placed only this part of the form since this is the only part that doesn't work. Thank you in advance.

Upvotes: 1

Views: 8900

Answers (1)

Raz Ronen
Raz Ronen

Reputation: 2638

this.formBuilder.group({
    stepName: new FormControl('', [Validators.required]),
    stepDesc: new FormControl('', [Validators.required]),
  })

should be called before ngAfterViewInit is reached. Usually in the constructor/ngOnInit.

Upvotes: 5

Related Questions