【问题标题】:How can i fix Error: formControlName must be used with a parent formGroup directive. - Angular ReactiveForms FormBuilder如何修复错误:formControlName 必须与父 formGroup 指令一起使用。 - Angular ReactiveForms FormBuilder
【发布时间】:2021-04-17 18:33:22
【问题描述】:

我收到此错误:

ERROR Error: formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).

我已经在 module.ts 中导入了import { ReactiveFormsModule } from '@angular/forms';

这是模板 .html:

<mat-step [stepControl]="bankFormGroup" label="Some label">
    <form [formGroup]="bankFormGroup">
        <mat-form-field>
            <mat-label>Banco</mat-label>
            <mat-select ngDefaultControl formControlName="bank">
                <mat-option *ngFor="let bank of banks" value="{{bank.id}}">
                    {{bank.id}} - {{bank.name}}
                </mat-option>
            </mat-select>             
        </mat-form-field>
        <mat-form-field>
            <mat-label>Agência</mat-label>
            <input matInput formControlName="agency" placeholder="0001">                
        </mat-form-field>
        <mat-form-field>
            <mat-label>Número da Conta Corrente</mat-label>
            <input matInput formControlName="account" placeholder="26262661">                
        </mat-form-field>
        {...action form}
    </form>
</mat-step>

这是component.ts:

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

export class UploadComponent {
  
  bankFormGroup: FormGroup = this._formBuilder.group({
    bank: ['', Validators.required],
    agency: ['', Validators.required],
    account: ['', Validators.required]
  });
  banks: any[] = [
    { id: '001', name: 'Banco do Brasil S.A.' },
    { id: '237', name: 'Banco Bradesco S.A.' },
  ];

 constructor(private _formBuilder: FormBuilder) { }

}

我已经在其他页面中看到了类似的其他问题,例如 https://stackoverflow.com/questions/43305975 。但我仍然无法消除这个问题。

我正在使用:

"@angular/forms": "^11.0.0",
"@angular/core": "^11.0.0",
"@angular/material": "^11.0.3",

【问题讨论】:

  • 错误在同一个组件中以另一种形式出现。没有&lt;form [formGroup]="FormGroupName"&gt;父的另一种形式...

标签: angular-material angular-reactive-forms angular2-formbuilder


【解决方案1】:

错误在同一组件中以另一种形式出现。没有&lt;form [formGroup]="FormGroupName"&gt;父的另一种形式..

用[formGroup]检查是否有另一个没有父容器的表单

【讨论】:

    猜你喜欢
    • 2018-03-09
    • 2018-10-03
    • 2018-01-31
    • 2020-04-07
    • 2017-09-04
    • 1970-01-01
    • 2020-02-06
    • 2019-09-28
    • 2020-01-25
    相关资源
    最近更新 更多