如何修复Angular FormArray错误:找不到具有未指定名称属性的控件

时间:2019-01-06 23:17:44

标签: angular forms typescript formarray

我尝试使用表单数组创建react表单。但是我收到一个错误:“找不到具有未指定名称属性的控件”。

我看了这个网站 https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2

我从堆栈溢出的其他问题中尝试了很少的解决方案,但对我来说不起作用(可能是由于我的知识不足)

以下是我尝试修复的错误。

'injury-condition-found.component.html'

  1. [formGroup] =“ injuryFoundForm” => formGroup =“ injuryFoundForm”。
  2. [formGroupName] =“ i” => formGroupName =“ i”

'detail-injury-form.component.html'

  1. [formGroup] =“ detailInjuryForm” => formGroup =“ detailInjuryForm”

这是我的代码

'injury-condition-found.component.ts'

export class InjuryConditionFoundComponent implements OnInit { 
injuryFoundForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    /**
     * Create Form group
     */
    this.injuryFoundForm = this.fb.group({
      noInjury: false,
      details: this.fb.array([
        this.initDetail()
      ])
    });
  }

  initDetail(){
    return this.fb.group({
      treatment: null,
      unknown: null
    });
  }

  addDetail(){
    const control = <FormArray>this.injuryFoundForm.controls['details'];
    control.push(this.initDetail());
  }

  deleteDetail(i: number){
    const control = <FormArray>this.injuryFoundForm.controls['details'];
    control.removeAt(i);
  }
}

'injury-condition-found.component.html'

<div [formGroup]="injuryFoundForm">
    <mat-checkbox formControlName="noInjury"></mat-checkbox>

    <div [formGroupName]="i" *ngFor="let item of injuryFoundForm.controls.details.controls">
        <app-detail-injury-form 
            [group]="injuryFoundForm.controls.details.controls[i]"
            (deleteClicked)="deleteInjuryForm(i)">
        </app-detail-injury-form>
    </div>
</div>

'detail-injury-form.component.ts'

export class DetailInjuryFormComponent implements OnInit {
    @Output() deleteClicked: EventEmitter<number> = new EventEmitter();
    @Input('group') public detailInjuryForm: FormGroup;

    deleteDetailInjury(){
        this.deleteClicked.emit(this.id);
    }

    ngOnInit() {
        this.detailInjuryForm = this.fb.group({
            treatment: null,
            unknown: null
        });
    }
}

'detail-injury-form.component.html'

<mat-accordion [formGroup]="detailInjuryForm">
    <mat-expansion-panel>
        <mat-expansion-panel-header>
            <mat-panel-title>
                <button (click)="deleteDetailInjury()">Delete</button>
            </mat-panel-title>
        </mat-expansion-panel-header>

        <label>Unknown Behavior</label>
        <textarea rows="4" formControlName="unknown"></textarea>

        <label>Treatment Notes</label><br>
        <textarea rows="4" formControlName="treatment"></textarea>
    </mat-expansion-panel>
</mat-accordion>

错误错误:找不到具有未指定名称属性的控件

我是新开发人员,对我的混乱代码感到抱歉。 我的项目中有更多代码,但是我在对这个问题不重要的地方剪切了代码。 问候

0 个答案:

没有答案