表单控件无值访问器如何解决?

问题描述 投票:0回答:1

我无法在 Angular 18 版本上找到此错误 我添加了表单模块以及公共模块。

<div class="col-lg-4 col-md-4 col-sm-4">
                    <div class="form__group">
                        <input type="text" class="form__field" placeholder=" " [(ngModel)]="AddUpdatePaymentModel.Bank" formControlName="Bank" id="fname">
                        <label for="fname" class="form__label">Bank </label>
                    </div>                
                </div>

https://i.sstatic.net/kE1E8hVb.png

以上是我的错误

我已经应用了以下解决方案,但它没有按预期工作。

 providers: [
{
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => MyComponent),
  multi: true
}

],

angular typescript
1个回答
0
投票

您面临的错误可能是由于 Angular Reactive Forms 中

[(ngModel)]
formControlName
之间的冲突造成的。您不应该在同一表单元素中使用两者。要解决此问题,您可以使用模板驱动表单(使用
[(ngModel)]
)或反应式表单(使用
formControlName
),但不能同时使用两者。

修复方法如下:

  1. 如果您使用反应式表单: 删除
    [(ngModel)]
    绑定并仅使用
    formControlName
    :
<div class="col-lg-4 col-md-4 col-sm-4">
    <div class="form__group">
        <input type="text" class="form__field" placeholder=" " formControlName="Bank" id="fname">
        <label for="fname" class="form__label">Bank</label>
    </div>                
</div>

确保您已根据需要将

FormBuilder
FormGroup
添加到组件中:

this.paymentForm = this.formBuilder.group({
  Bank: ['']
});
  1. 如果您使用模板驱动表单: 删除
    formControlName
    并仅使用
    [(ngModel)]
    : html
银行

此外,请确保您已在模块文件中导入了必要的模块: 打字稿 从 '@angular/forms' 导入 { FormsModule, ReactiveFormsModule };

@NgModule({ 进口:[ 通用模块, 表单模块, 反应式表单模块 ] })


Summary:
- For reactive forms, use `formControlName` only.
- For template-driven forms, use `[(ngModel)]` only.

Make sure you're consistent with your form approach across the app. Let me know if this resolves your issue!
© www.soinside.com 2019 - 2024. All rights reserved.