在 Recative 表单中使用 formArray 时出现“TypeError:

我正在使用 formArray 创建动态表单。但是我遇到了“类型错误:无法读取未定义的属性‘控件’”


enter code here

import { Component, OnInit } from '@angular/core';

import { FormGroup, FormBuilder, FormArray } from '@angular/forms';

@Component({

 selector: 'app-root',

 templateUrl: './app.component.html',

 styleUrls: ['./app.component.css']

})

 export class AppComponent implements OnInit {

 title = 'Trainner Registration Form ';

 registrationForm: FormGroup;


 get LanguagesForm() {

    return this.registrationForm.get('Languages') as FormArray;

 }


 addLanguage() {

  this.LanguagesForm.push(this.fb.control(''));

}



 constructor(private  fb : FormBuilder ) {}

   ngOnInit(){

     this.registrationForm = this.fb.group({

      personalDetails : this.fb.group({

      name: this.fb.group({

        firstName: [''],

        lastName: ['']

      }),

      aboutYours: [''],

      dob: [''],

      // lang: [''],

      Languages: this.fb.array([]),

      wTT: ['']

    })

  });


}



onSubmit() {

  console.log(this.registrationForm.value);

  // this._registerationservice.register(this.registrationForm.value).subscribe(

  //   response => console.log('Success', response),

  //   error => console.log('Error',error)

  // );

}

}


预期结果:如果用户单击“添加语言”按钮,则应创建一个新的输入字段。


实际结果:我收到“类型错误:无法读取未定义的属性‘控件’”


智慧大石
浏览 198回答 3
3回答

牛魔王的故事

发生这种情况是因为您没有设置上层 formGroup,personalDetails因此 reyLanguages在registrationForm控件中查找带有名称的控件,其中Languages控件是personalDetails表单组中的控件,另一件与您有拼写错误相关的内容LanguagesForm.controls必须是“Languages.controls”<div class="form-group">&nbsp; <label>Language(s) : </label>&nbsp; <button type="button" class="btn btn-secondary btn-sm m-2" (click)="addLanguage()">Add Language</button>&nbsp; <div [formGroup]="registrationForm"> <!-- 👈 -->&nbsp; &nbsp; <div [formGroupName]="'personalDetails'"> <!-- 👈 -->&nbsp; &nbsp; &nbsp; <div formArrayName="Languages">&nbsp; &nbsp; &nbsp; &nbsp; <div *ngFor="let lag of registrationForm.get('personalDetails').get('Languages').controls; let i =index;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" class="form-control" [formControlName]="i">&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; </div></div>您可以使用 get 属性来访问这样的语言表单&nbsp; langsform() :FormArray {&nbsp;&nbsp; &nbsp; return this.registrationForm.get('personalDetails').get('Languages') as FormArray&nbsp;&nbsp; }模板<div [formGroup]="registrationForm">&nbsp; <div [formGroupName]="'personalDetails'">&nbsp; &nbsp; <div formArrayName="Languages">&nbsp; &nbsp; &nbsp; <div *ngFor="let lang of langsform.controls; let i =index;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" class="form-control" [formControlName]="i">&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; </div></div>

潇潇雨雨

我认为问题是你在 onInit 中初始化了 registrationForm 对象,此时模板已经被解析,所以你应该*ngIf="this.registrationForm"在这个 div 上添加一个<div formArrayName="Languages">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript