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

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


当前回答

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

其他回答

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

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

我也有同样的误差,角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}}

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

所以我只需要改变:

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

to:

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

ts:

@Input()
control:FormControl;

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

当你在一个不能有<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