下面是我的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>
    `
} )

这是我的班级:

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;
    }
}

这是我编译时得到的错误:

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)

当我改变元素开关输入它工作,知道我使用相同的结构到其他组件,它工作得很好。


我通过在带有[(ngModel)]属性的元素中添加name="fieldName" ngDefaultControl属性来修正这个错误。


我有同样的问题,问题是我的子组件有一个名为formControl的@input。

所以我只需要改变:

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

to:

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

ts:

@Input()
control:FormControl;

这是一种愚蠢的,但我得到这个错误消息,不小心使用[formControl]而不是[formGroup]。在这里看到的:

错误的

@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: ''
    })
  }
}

正确的

@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: ''
    })
  }
}

我在Angular 7中编写自定义表单控件组件时也收到过这个错误。然而,这些答案都不适用于Angular 7。

在我的例子中,需要将以下内容添加到@Component装饰器中:

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

这是一个“我不知道为什么它有效,但它确实有效”的案例。这要归咎于Angular糟糕的设计/实现。


我也有同样的误差,角7

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

我刚刚添加了ngDefaultControl

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


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


在我的情况下,我使用指令,但没有导入它在我的模块。ts文件。Import修复了它。


在我的例子中,我在标签而不是输入中插入了[(ngModel)]。 还有一个警告,我尝试正确地运行上述错误在指定的行,但错误不会去。如果您在其他地方犯了相同的错误,它仍然会在同一行向您抛出相同的错误


我有同样的错误,但在我的情况下,这显然是一个同步问题,在呈现组件html的时刻。

我遵循了本页上提出的一些解决方案,但它们都对我有效,至少不是完全有效。

真正解决我的错误的是在元素的父html标记中编写下面的代码片段。

我绑定了变量。

代码:

    *ngIf="variable-name"

该错误显然是由项目试图渲染页面引起的,显然在评估变量的时候,项目就是找不到它的值。使用上面的代码片段,您可以确保在呈现页面之前询问变量是否已初始化。

这是我的分量。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));
    });
  }
      ...

这是我的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">
             ...

我希望这能对你有所帮助。


我有同样的错误,我在我的自定义表单组件中有一个名为control的输入字段,但无意中传递了名为formControl的输入控件。希望没有人面临这样的问题。


我在运行Karma单元测试用例时遇到了这个错误 在导入中添加MatSelectModule可以解决这个问题

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

你有没有试过移动你的[(ngModel)]到div而不是在你的HTML开关?我在我的代码中出现了同样的错误,这是因为我将模型绑定到<mat-option>而不是<mat-select>。虽然我没有使用表单控件。


在我的例子中,它是一个组件。不存在的成员。

[formControl]="personId"

将其添加到类声明中可以解决这个问题

this.personId = new FormControl(...)

我在Jasmine的单元测试中得到了这个错误消息。我添加了ngDefaultControl属性自定义元素(在我的情况下,这是一个角度材料滑动切换),这解决了错误。

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

将上面的元素修改为包含ngDefaultControl属性

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

在我的情况下,我有一个<TEXTAREA>标签从旧的html转换到angular。必须更改为<textarea>。


在我的例子中,它发生在我的共享模块中,我必须将以下内容添加到@NgModule中:

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

在我的情况下,这就像在我的app.module.ts声明中为DI注册了新组件而不是在exports中一样愚蠢。


在我的例子中,错误是由于在模块中复制导入组件而触发的。


#背景

NativeScript 6.0

在我的例子中,错误是由将元素标签从更改为by fault触发的。<TextView an [(ngModel)]="name"。被定义。

删除[(ngModel)]="name"错误消失。


我在运行单元测试时遇到了这个问题。为了解决这个问题,我在我的spec.ts文件中添加了MatSlideToggleModule的导入。


我还收到了这个错误,当我命名我的一个组件输入'formControl'。可能是留给别的东西用的。如果你想在组件之间传递FormControl对象,可以这样使用:

@Input() control: FormControl;

不是这样的:

@Input() formControl: FormControl;

奇怪-但有效:)


如果你试图将ngModel添加到非输入元素中,比如<option> HTML标签,也会出现这个错误。确保你只把ngModel添加到<input>标签。 在我的例子中,我已经添加了一个ngModel到<ion-select-option>而不是<ion-select>。


在我的情况下,我忘记添加提供商:[INPUT_VALUE_ACCESSOR]到我的自定义组件

我有INPUT_VALUE_ACCESSOR创建为:

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

在我的情况下,问题是我创建了一个@Input变量与保留名称formControl。


我在mat-select中使用了一个formControl:

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

我意识到MatSelectModule没有在规范文件中导入,这解决了这个问题。


如果这对某些人有帮助,我得到这个错误,因为我在选择的选项标签内有ngModel。

由于(我的)错误,我得到了这个:

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

而不是这样:

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

它看起来像“formControl”是Angular表单的保留名称,当我使用这个名称作为组件的输入时,我在实际的from控件中得到了意想不到的行为。如果你问我,我会说这是Angular的一个bug。只需将您的输入名称替换为“frmCtrl”或其他东西,它就会工作。


我也犯了同样的错误,只需要在module.ts中导入表单模块

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

当我尝试集成angular编辑器时,我也面临着同样的问题

我通过添加[ngModelOptions]="{standalone: true}"到我的标签来解决这个问题。

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

我希望这是最快的解决方案参考


当你在一个不能有<div>这样值的元素上使用ngModel或formControl时,就会发生这种情况。

当ngModel或formControl像这样使用时会出现问题:

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

解决方案:

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

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


我还创建了一个自定义控件。 解决此问题的方法如下:

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