简体   繁体   English

ERROR 错误:在开关上没有具有未指定名称属性的表单控件的值访问器

[英]ERROR Error: No value accessor for form control with unspecified name attribute on switch

Here is my Angular component:这是我的 Angular 组件:

@Component( {
    selector: 'input-extra-field',
    template: `
            <div class="form-group" [formGroup]="formGroup" >
                <switch [attr.title]="field.etiquette" 
                    [attr.value]="field.valeur" [(ngModel)]="field.valeur"
                    [formControl]="fieldControl" [attr.id]="name" [attr.disabled]="disabled">
                </switch>
                <error-messages [control]="name"></error-messages>
            </div>
    `
} )

Here is my Class:这是我的课:

export class SwitchExtraField extends ExtraField {
    @Input() field: ExtraFormField;
    @Input() entity: { fields: Object };
    @Input() formGroup: FormGroup;

    constructor( formDir: NgForm ) {
        super( null, null, formDir );
    }

    get disabled(): string {
        if ( this.field && !!this.field.saisissable && !this.field.saisissable )     {
            return 'disabled';
        }
        return null;
    }
}

This is the error I get when compiling:这是我在编译时遇到的错误:

ERROR Error: No value accessor for form control with unspecified name attribute
  at _throwError (forms.es5.js:1918)
  at setUpControl (forms.es5.js:1828)
  at FormControlDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormControlDirective.ngOnChanges (forms.es5.js:4617)

When I change the element switch to input it works, knowing that I'm using the same structure to other components and it works fine.当我将元素开关更改为输入时,它可以工作,因为我知道我对其他组件使用相同的结构并且它工​​作正常。

我通过将name="fieldName" ngDefaultControl属性添加到带有[(ngModel)]属性的元素来修复此错误。

I had the same problem and the issue was that my child component had an @input named formControl .我遇到了同样的问题,问题是我的子组件有一个名为formControl@input

So I just needed to change from:所以我只需要改变:

<my-component [formControl]="formControl"><my-component/>

to:至:

<my-component [control]="control"><my-component/>

ts: ts:

@Input()
control:FormControl;

I also received this error while writing a custom form control component in Angular 7. However, none of the answers are applicable to Angular 7.在 Angular 7 中编写自定义表单控件组件时,我也收到了这个错误。但是,没有一个答案适用于 Angular 7。

In my case, the following needed to be add to the @Component decorator:在我的情况下,需要将以下内容添加到@Component装饰器中:

  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => MyCustomComponent),  // replace name as appropriate
      multi: true
    }
  ]

This is a case of "I don't know why it works, but it does."这是一个“我不知道它为什么有效,但它确实有效”的案例。 Chalk it up to poor design/implementation on the part of Angular.将其归结为 Angular 的糟糕设计/实现。

I also had the same error , angular 7我也有同样的错误,角度 7

 <button (click)="Addcity(city.name)" [(ngModel)]="city.name"  class="dropdown-item fontstyle"
     *ngFor="let city of Cities; let i = index">
      {{city.name}}
 </button>

I just added ngDefaultControl我刚刚添加了ngDefaultControl

   <button (click)="Addcity(city.name)" [(ngModel)]="city.name"  ngDefaultControl class="dropdown-item fontstyle"
 *ngFor="let city of Cities; let i = index">
  {{city.name}}

I was facing this error while running Karma Unit Test cases Adding MatSelectModule in the imports fixes the issue我在运行 Karma 单元测试用例时遇到了这个错误在导入中添加MatSelectModule修复了这个问题

imports: [
        HttpClientTestingModule,
        FormsModule,
        MatTableModule,
        MatSelectModule,
        NoopAnimationsModule
      ],

I was getting this error message in my Unit tests with Jasmine.我在 Jasmine 的单元测试中收到此错误消息。 I added ngDefaultControl attribute to the custom element(in my case it was an angular material slide toggle) and this resolves the error.我向自定义元素添加了ngDefaultControl属性(在我的情况下,它是一个有角度的材质幻灯片切换),这解决了错误。

<mat-slide-toggle formControlName="extraCheese">
  Extra Cheese
</mat-slide-toggle>

Change the above element to include ngDefaultControl atttribute更改上述元素以包含ngDefaultControl属性

<mat-slide-toggle ngDefaultControl formControlName="extraCheese">
 Extra Cheese
</mat-slide-toggle>

In my case I forgot to add providers: [INPUT_VALUE_ACCESSOR] to my custom component就我而言,我忘记将providers: [INPUT_VALUE_ACCESSOR]添加到我的自定义组件中

I had INPUT_VALUE_ACCESSOR created as:我将 INPUT_VALUE_ACCESSOR 创建为:

export const INPUT_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => TextEditorComponent),
  multi: true,
};

我遇到了同样的错误——我不小心将 [(ngModel)] 绑定到我的mat-form-field而不是input元素。

I also received this error when I named one of my component inputs 'formControl'.当我将其中一个组件输入命名为“formControl”时,我也收到了此错误。 Probably it's reserved for something else.可能它是为其他东西保留的。 If you want to pass FormControl object between components, use it like that:如果要在组件之间传递 FormControl 对象,请像这样使用它:

@Input() control: FormControl;

not like this:不是这样的:

@Input() formControl: FormControl;

Weird - but working :)奇怪 - 但工作:)

This is kind of stupid, but I got this error message by accidentally using [formControl] instead of [formGroup] .这有点愚蠢,但我不小心使用[formControl]而不是[formGroup]得到了这个错误消息。 See here:看这里:

WRONG错误的

@Component({
  selector: 'app-application-purpose',
  template: `
    <div [formControl]="formGroup"> <!-- '[formControl]' IS THE WRONG ATTRIBUTE -->
      <input formControlName="formGroupProperty" />
    </div>
  `
})
export class MyComponent implements OnInit {
  formGroup: FormGroup

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      formGroupProperty: ''
    })
  }
}

RIGHT正确的

@Component({
  selector: 'app-application-purpose',
  template: `
    <div [formGroup]="formGroup"> <!-- '[formGroup]' IS THE RIGHT ATTRIBUTE -->
      <input formControlName="formGroupProperty" />
    </div>
  `
})
export class MyComponent implements OnInit {
  formGroup: FormGroup

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      formGroupProperty: ''
    })
  }
}

In my case i used directive, but hadn't imported it in my module.ts file.在我的情况下,我使用了指令,但没有将它导入到我的 module.ts 文件中。 Import fixed it.导入修复它。

就我而言,问题是我使用保留名称formControl创建了一个@Input变量。

In my case, it was happening in my shared module and I had to add the following into @NgModule:就我而言,它发生在我的共享模块中,我必须将以下内容添加到@NgModule:

...
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    IonicModule
  ],
...

In my case, I had inserted [(ngModel)] on label rather than input.就我而言,我在标签上插入了 [(ngModel)] 而不是输入。 There is also a caveat, I tried running after correctly the above error in the specified line but the error wouldn't go.还有一个警告,我尝试在指定行中正确运行上述错误但错误不会消失。 If there are other places where you have committed the same mistake, it still throws you the same error at the same line如果您在其他地方犯了同样的错误,它仍然会在同一行抛出同样的错误

This error also occurs if you try to add ngModel to the non-input elements like <option> HTML tags.如果您尝试将 ngModel 添加到<option> HTML 标签等非输入元素,也会发生此错误。 Make sure you add ngModel only to the <input> tags.确保只将 ngModel 添加到<input>标签。 In my case, I have added a ngModel to the <ion-select-option> instead of <ion-select> .就我而言,我已将 ngModel 添加到<ion-select-option>而不是<ion-select>

I was using a formControl in a mat-select like this:我在 mat-select 中使用了 formControl,如下所示:

<mat-select [formControl]="control">
 ...
</mat-select>

and I realized that MatSelectModule was not imported in the spec file, that solved the issue.我意识到 MatSelectModule 没有导入到规范文件中,这解决了这个问题。

If this helps somebody, I was getting this error cause I had the ngModel inside the option tag on a select.如果这对某人有帮助,我会收到此错误,因为我在选择的选项标签内有 ngModel。

By mistake (mine), I had this:错误地(我的),我有这个:

<select class="form-control">
    <option *ngFor="let mystate of data.states" value="{{mystate.stateAbbreviation}}" [(ngModel)]="dependent.state">{{mystate.stateName}}</option>
</select>

Instead of this:而不是这个:

<select class="form-control" [(ngModel)]="dependent.state">
    <option *ngFor="let mystate of data.states" value="{{mystate.stateAbbreviation}}" >{{mystate.stateName}}</option>
</select>

I had this same error, I had a input field named control in my custom Form Component but was accidentally passing control in input named formControl .我遇到了同样的错误,我的自定义表单组件中有一个名为control的输入字段,但意外地在名为formControl的输入中传递了控件。 Hope no one faces that issue.希望没有人面临这个问题。

就我而言,这就像在我的app.module.ts声明中为 DI 注册新组件但在导出中没有注册一样愚蠢。

I had the same error, but in my case apparently it was a synchronization issue, at the moment of render the components html.我有同样的错误,但在我的情况下,显然这是一个同步问题,在渲染组件 html 时。

I followed some of the solutions proposed on this page but any of them worked for me, at least not completely.我遵循了此页面上提出的一些解决方案,但其中任何一个都对我有用,至少不完全。

What did actually solve my error was to write the below code snippet inside the father html tag of the elements .真正解决我的错误的是在元素的父 html 标记内编写以下代码片段。

I was binding to the variable.我正在绑定到变量。

Code:代码:

    *ngIf="variable-name"

The error was caused, apparently by the project trying to render the page, apparently at the moment of evaluating the variable, the project just could no find its value.该错误显然是由项目试图渲染页面引起的,显然在评估变量的那一刻,项目只是找不到它的值。 With the above code snippet you make sure that before rendering the page you ask if the variable has being initialized.使用上面的代码片段,您可以确保在呈现页面之前询问变量是否已初始化。

This is my component.ts code:这是我的 component.ts 代码:

import { Component, OnInit } from '@angular/core';
import { InvitationService } from 'src/app/service/invitation.service';
import { BusinessService } from 'src/app/service/business.service';
import { Invitation } from 'src/app/_models/invitation';
import { forEach } from '@angular/router/src/utils/collection';

@Component({
  selector: 'app-invitation-details',
  templateUrl: './invitation-details.component.html',
  styleUrls: ['./invitation-details.component.scss']
})
export class InvitationDetailsComponent implements OnInit {
  invitationsList: any;
  currentInvitation: any;
  business: any;
  invitationId: number;
  invitation: Invitation;

  constructor(private InvitationService: InvitationService, private BusinessService: 
BusinessService) { 
this.invitationId = 1; //prueba temporal con invitacion 1
this.getInvitations();
this.getInvitationById(this.invitationId);
  }

   ngOnInit() {

  }

  getInvitations() {
    this.InvitationService.getAllInvitation().subscribe(result => {
      this.invitationsList = result;
      console.log(result);
    }, error => {
      console.log(JSON.stringify(error));
    });
  }

  getInvitationById(invitationId:number){
    this.InvitationService.getInvitationById(invitationId).subscribe(result => {
      this.currentInvitation = result;
      console.log(result);
      //this.business=this.currentInvitation['business'];
       //console.log(this.currentInvitation['business']); 
     }, error => {
     console.log(JSON.stringify(error));
    });
  }
      ...

Here is my html markup:这是我的 html 标记:

<div class="container-fluid mt--7">
  <div class="row">
    <div class="container col-xl-10 col-lg-8">
      <div class="card card-stats ">
        <div class="card-body container-fluid form-check-inline" 
         *ngIf="currentInvitation">
          <div class="col-4">
             ...

I hope this can be helpful.我希望这会有所帮助。

Have you tried moving your [(ngModel)] to the div instead of the switch in your HTML?您是否尝试过将[(ngModel)]移动到div而不是 HTML 中的switch I had the same error appear in my code and it was because I bound the model to a <mat-option> instead of a <mat-select> .我的代码中出现了同样的错误,这是因为我将模型绑定到<mat-option>而不是<mat-select> Though I am not using form control.虽然我没有使用表单控件。

In my case it was a component.member which was not existing eg在我的情况下,它是一个不存在的 component.member 例如

[formControl]="personId"

Adding it to the class declaration fixed it将其添加到类声明中修复了它

this.personId = new FormControl(...)

I was facing this issue while running unit tests.我在运行单元测试时遇到了这个问题。 To fix I added the MatSlideToggleModule to the imports in my spec.ts file.为了解决这个问题,我将 MatSlideToggleModule 添加到我的 spec.ts 文件中的导入中。

It is looks like "formControl" is reserved name by Angular Forms, when I used this name as an input to my component, I got unexpected behavior with my actual from control.看起来“formControl”是Angular Forms的保留名称,当我将此名称用作组件的输入时,我的实际控制出现了意外行为。 If you ask me, this is an Angular bug.如果你问我,这是一个 Angular 错误。 Just replace your input name to something else like "frmCtrl" or whatever, and it will work.只需将您的输入名称替换为“frmCtrl”或其他名称,它就会起作用。

在我的情况下,错误是由复制模块中的组件导入触发的。

#Background #背景

  • NativeScript 6.0原生脚本 6.0

In my case, the error was triggered by changing element tag from to by fault.在我的情况下,错误是通过将元素标签从故障更改为触发的。 Inside <TextView an [(ngModel)]="name".在 <TextView 内部是一个 [(ngModel)]="name"。 was defined.被定义。

After removing [(ngModel)]="name" error was gone.删除 [(ngModel)]="name" 后错误消失了。

I had the same error just need to import forms module in module.ts我有同样的错误只需要在 module.ts 中导入表单模块

import { FormsModule } from '@angular/forms';
    
@NgModule({
    imports: [FormsModule]
)}

I'm facing the same problem when I try to integrate angular editor当我尝试集成角度编辑器时,我遇到了同样的问题

I resolve that by adding [ngModelOptions]="{standalone: true}" to my tag.我通过将[ngModelOptions]="{standalone: true}"添加到我的标签来解决这个问题。

<angular-editor [ngModelOptions]="{standalone: true}" [(ngModel)]="htmlContent" [config]="config"></angular-editor>

I hope it's the quickest solution reference我希望这是最快的解决方案参考

This happens when you use ngModel or formControl on an element which cannot have a value like a <div> element.当您在不能具有<div>元素之类的值的元素上使用 ngModel 或 formControl 时,会发生这种情况。

Problem occurs when ngModel or formControl is used like this:像这样使用 ngModel 或 formControl 时会出现问题:

<div [(ngModel)]="myModel"> <--- wrong place
    <input type="text" />
</div>

Solution:解决方案:

<div>
    <input type="text" [(ngModel)]="myModel" /> <--- correct place
</div>

Source: https://github.com/angular/angular/issues/43821#issuecomment-992305494来源: https ://github.com/angular/angular/issues/43821#issuecomment-992305494

I also created a custom control.我还创建了一个自定义控件。
The following resolved this issue:以下解决了这个问题:

constructor(
  @Optional() @Self()
  readonly ngControl: NgControl,
) {
  this.ngControl.valueAccessor = this;
}

in my case, I had a <TEXTAREA> tag from old html while converting to angular.就我而言,我在转换为 angular 时有一个来自旧 html 的<TEXTAREA>标记。 Had to change to <textarea> .不得不更改为<textarea>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误错误:具有未指定名称属性的表单控件没有值访问器 - ERROR Error: No value accessor for form control with unspecified name attribute 表单控件错误:错误错误:没有具有未指定名称属性的表单控件的值访问器 - form control error:ERROR Error: No value accessor for form control with unspecified name attribute ERROR 错误:在 angular 中绑定轮播时,没有具有未指定名称属性的表单控件的值访问器 - ERROR Error: No value accessor for form control with unspecified name attribute when bind carousel in angular Angular 7-具有未指定名称属性的表单控件无值访问器 - Angular 7 - No value accessor for form control with unspecified name attribute Angular 7 Reactive 表单“没有未指定名称属性的表单控件的值访问器” - Angular 7 Reactive forms “No value accessor for form control with unspecified name attribute” 没有用于未指定名称属性Angular 2的表单控件的值访问器 - No value accessor for form control with unspecified name attribute Angular 2 没有用于ngControl的未指定名称属性的表单控件的值访问器 - No value accessor for form control with unspecified name attribute for ngControl 没有用于角度控制的格式控件的值访问器(角度5中具有未指定的名称属性) - No value accessor for form control with unspecified name attribute in angular 5 以Angular格式显示img会显示“没有用于未指定名称属性的窗体控制的值访问器” - Displaying img in Angular form gives “No value accessor for form control with unspecified name attribute” 没有用于角度控制的表单控制的值访问器,角度7中的名称错误 - No value accessor for form control with name error in angular 7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM