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

不羁的心 提交于 2019-11-26 19:57:09

问题


Here is my component in Angular 4:

@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.


回答1:


I fixed this error by adding the name="fieldName" ngDefaultControl attributes to the element that carries the [(ngModel)] attribute.




回答2:


I had the same problem and the issue was that my child component had an @input named formControl.

So I just needed to change from:

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

to:

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

ts:

@Input()
control:FormControl;



回答3:


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.

In my case, the following needed to be add to the @Component decorator:

  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.




回答4:


I also had the same error , 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>

I just added ngDefaultControl

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




回答5:


This is kind of stupid, but I got this error message by accidentally using [formControl] instead of [formGroup]. See here:

WRONG

@Component({
  selector: 'app-application-purpose',
  template: `
    <div [formControl]="formGroup">
      <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">
      <input formControlName="formGroupProperty" />
    </div>
  `
})
export class MyComponent implements OnInit {
  formGroup: FormGroup

  constructor(
    private formBuilder: FormBuilder
  ) { }

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



回答6:


I was facing this error while running Karma Unit Test cases Adding MatSelectModule in the imports fixes the issue

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



回答7:


I had this same error- I accidentally binded [(ngModel)] to my mat-form-field instead of the input element.




回答8:


In my case i used directive, but hadn't imported it in my module.ts file. Import fixed it.




回答9:


In my case, I had inserted [(ngModel)] on label rather than input. 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




回答10:


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. Hope no one faces that issue.




回答11:


I had the same error, but in my case apparently it was a synchronization issue, at the moment of render the components 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 .

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:

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:

<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.



来源:https://stackoverflow.com/questions/46422007/error-error-no-value-accessor-for-form-control-with-unspecified-name-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!