typescript 错误错误:formGroup需要一个FormGroup示例,在动态窗体中

cgfeq70w  于 2022-12-27  发布在  TypeScript
关注(0)|答案(1)|浏览(115)

我正在用这些数据创建动态表单控件

"data": [
            {
                "sno": 1,
                "name": "name",
                "nameLabel": "Name",
                "isRequired": 1,
                "maxLen": 50,
                "order": 1,

            },
            {
                "sno": 2,
                "name": "desc",
                "nameLabel": "Description",
                "isRequired": 1,
                "maxLen": 50,
                "order": 2,
            },
            ..
            ..

在Oninit方法中

rForm: FormGroup;
  Data:any=[];
  ngOnInit(): void {
    let json = {
      ....
    }
    this.Service.Info(json).subscribe((data) => {
   
      this.Data=data;
     for (const field of this.Data) {
      let validators = [];
      validators.push(Validators.required);
      this.rForm.addControl(field.name, this.fb.control('', validators));
    }
    });
  }

html组件中使用此

<form *ngIf="Data?.length" [formGroup]="rForm">
            <div class="col-lg-4 col-md-12 col-12" >
                <div class="form-group">
                    <label for="">Email</label>
                    <input type="text" class="form-control" placeholder="Email">
                </div>
            </div>

但无法呈现动态场
错误错误:formGroup需要一个FormGroup示例。请传入一个示例。
任何解决方案来解决这个问题。谢谢

nlejzf6q

nlejzf6q1#

首先,ngOnInit代码应该如下所示

ngOnInit(): void {
  this.Service.Info(json).subscribe((data) => {
    this.Data = data.data;
    for (const field of this.Data) {
      let validators = [];
      validators.push(Validators.required);
      this.rForm.addControl(field.name, this.fb.control('', validators));
    }
  });
 }
    • 超文本标记语言**
<form *ngIf="Data != null && Data.length > 0" [formGroup]="rForm">
    <div class="col-lg-4 col-md-12 col-12">
        <div class="form-group" *ngFor="let control of rForm.value | keyvalue">
            <label for="">Email</label>
            <input type="text" class="form-control" placeholder="Email" [formControlName]="control.key">
            <span *ngIf="form.get(control.key).errors?.required">Field is required</span>
        </div>
    </div>
</form>

你需要确定的另一点是

    • *[formControlName]="email"**传递不存在的属性email的值。您需要传递字符串email,如[formControlName]= "'email '"或更简单的formControlName =" email "

相关问题