NG01203: The form control with the name 'name' does not have a specified value accessor

This question was originally posted by JOYBOY but was later deleted. The title of the question was NG01203: No value accessor for form control name: 'name'


In my Angular 18 application, I am utilizing both standalone components and module-based components for reusability purposes.

To enhance reusability, I have created an input component. However, I am encountering an error:

ERROR Error: NG01203: No value accessor for form control name: 'name'. Find more at https://angular.dev/errors/NG01203
    at _throwMissingValueAccessorError (forms.mjs:3420:9)
    at setUpControl (forms.mjs:3202:29)
    at _FormGroupDirective.addControl (forms.mjs:5320:5)
    at _FormControlName._setUpControl (forms.mjs:6011:39)
    at _FormControlName.ngOnChanges (forms.mjs:5960:28)
    at _FormControlName.rememberChangeHistoryAndInvokeOnChangesHook (core.mjs:3975:10)
    at callHookInternal (core.mjs:5004:10)
    at callHook (core.mjs:5031:5)
    at callHooks (core.mjs:4988:9)
    at executeInitAndCheckHooks (core.mjs:4943:5)
type InputProps = {
  formGroup: FormGroup;
  type: 'text' | 'password' | 'number';
  value: string;
  label: string;
  formControlName: string;
  placeholder: string;
  checkValidation: boolean;
}

@Component({
  selector: 'app-input',
  standalone: true,
  imports: [
    FormsModule,
    ReactiveFormsModule,
    NgClass
  ],
  templateUrl: './input.component.html',
})
export class InputComponent {

  public readonly formGroup = input.required<FormGroup>();
  public readonly label = input.required<InputProps['label']>();
  public readonly formControlName = input.required<InputProps['formControlName']>();
  public readonly checkValidation = input<InputProps['checkValidation']>(false);
  public readonly placeholder = input<InputProps['placeholder']>();

  public type = input<InputProps['type']>('text');
  public value = input<InputProps['value']>('');
}
input.component.html
<input
      [type]="type()"
      [id]="label()"
      [formControlName]="formControlName()"
      [ngClass]="inputBaseClasses"
      [value]="value()"
    />
    <label [for]="label()" [ngClass]="labelBaseClasses">
      {{ label() }}
    </label>
  </div>

I am including this input component in my AuthModule.ts

@NgModule({
  declarations: [
    LoginComponent,
    RegisterComponent,
    AuthComponent
  ],
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    AuthRoutingModule,
    AngularSvgIconModule.forRoot(),
    ButtonComponent,
    InputComponent
  ],
  exports: [
    FormsModule,
    ReactiveFormsModule
  ]
})
export class AuthModule { }

app.route.ts


export const routes: Routes = [
    {
        path: '',
        pathMatch: 'full',
        component: AppComponent
    },
    {
        path: 'auth',
        loadChildren: () => import('@app/core/auth/auth.module')
            .then(m => m.AuthModule)
    }
];

I am utilizing the app-input component like this:

<app-input 
      label="Name"
      formControlName="name" 
      [formGroup]="signUpForm" 
    ></app-input>

Even after exporting FormsModule & ReactiveFormsModule from AuthModule.ts, I am still encountering the error "no value accessor for form control : 'name'."

I am currently stuck and seeking guidance.

Answer №1

When you decide to create a custom form control, it's important to note that you usually don't need to specify the formControlName within the component definition itself.

By extending the ControlValueAccessor in your custom component, the binding to the form control is automatically taken care of.

Check out this tutorial for creating custom form controls

Here's an example Stackblitz for reference

The following modifications have been made to the code.

Initially, we encapsulate the custom component within the form that is bound to the formGroup. It's important to include the form control name within the custom component as well.

<form [formGroup]="signUpForm">
  <app-input 
    label="Name"
    formControlName="name" 
  ></app-input>
</form>

Subsequently, create the custom component control by referring to the provided links.

The form control name is removed from the component, and only an input event is added. The valueChanged function will store the updated value in the internal property _value.

valueChanged(val: string) {
  this.onChange(val);
}

Any changes made are captured by the input event, triggering the onChange event of the control, hence updating the actual form control.

On focus, the markAsTouched event is triggered.

The disabled flag is bound to the HTML through attributes.

The writeValue function is used to bind the value from the form control into the HTML.

writeValue(value: number) {
  this._value = value;
}

Complete Code:

(Code snippet provided. Please refer to the original source for the full code)

View the Stackblitz Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserve your NativeScript/Angular ImagePicker choice or retrieve the complete file path

After choosing an image with the Image Picker, I get a content// URL content://com.android.providers.media.documents/document/image%3A139 However, when using ImageSource.fromAsset(), I receive an empty object. My main objective is to save this image as a ...

Using Angular: How to access a component variable within a CSS file

I'm having issues with my css file and attempting to achieve the following: .login-wrapper { background-image: url({{imagePath}}); } Below is my component code: export class LoginComponent implements OnInit { imagePath: any = 'assets/discord ...

Looking for assistance with transforming my Angular 2 component into an npm package

After successfully creating a component in Angular 2, my next step is to convert it into an npm library for easy installation. npm install Despite installing Angular CLI and searching online, I have been unable to find clear instructions on how to effe ...

What is the best method for incorporating Angular 2 files into a Django template?

My application structure is set up like this: ├── project | |── templates │ │ └── index.html │ ├── __init__.py │ ├── models.py │ ├── urls.py │ ├── serializers.py │ ├── views.py ...

Utilizing StyleFunctionProps within JavaScript for Chakra UI Enhancements

I need help figuring out how to implement StyleFunctionProps in my Chakra UI theme for my NextJS project. The documentation on Chakra's website provides an example in Typescript, but I am working with Javascript. Can someone guide me on adapting this ...

What is the best method for incorporating CSS into an Angular application's embedded PowerBI report, which is displayed

Is there a way to incorporate external CSS or another method to apply styles to a PowerBI report embedded in an Angular application as an iframe? Specifically, I want to remove the scrollbar to ensure that the report seamlessly fits within the angular page ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

Utilizing AJAX or Angular in Django

I'm currently creating a blog platform with Django that allows users to post and comment. I've encountered an issue where adding a comment redirects the user to another page instead of staying on the same page. How can I utilize AJAX or AngularJS ...

Upon selecting an option in the mat-select element, the form does not update its pristine state to

I recently encountered an issue with my Angular Material mat-select form. I am populating the options from an observable and setting the selected item value programmatically, which is working fine. However, I faced a problem where I expected changing the m ...

Subscribe receives a value before it has been properly assigned

I am having trouble returning a value from the subscribe function in my code. Despite trying various solutions found online, I cannot get the function to wait for the value to be assigned before returning it. getMessage(field): string { this.service.get ...

Guide to Implementing Dependency Injection in Angular 2

When working with Angular Components written in TypeScript, it is possible to declare a class member (variable) as a parameter of the constructor. I am curious about the reason for doing so. To clarify, take a look at the examples below. Both achieve the ...

Error encountered on Firefox browser when saving content in TinyMCE editor: NS_ERROR_UNEXPECTED

We are currently experiencing an issue on the Firefox browser where our component with the tiny-mce editor displays an NS_ERROR_UNEXPECTED message and does not show any content upon reloading. Initially, when the editor loads for the first time, the conte ...

Angular 12 - Directing users to different views depending on their roles

In my situation, the Admin role login will be able to access the Home and UserView Component. After logging in, an Admin will automatically be taken to the Home component. On the other hand, the User role login will only have access to the UserView compone ...

Managing the activation and deactivation of a form based on value modifications

I have a formgroup with interconnected formcontrols where each control is enabled only if the previous one is filled. Additionally, if a control is cleared, all subsequent controls should also be cleared and disabled. To illustrate this use case, I create ...

Change the parent title attribute back to its original state

This is in contrast to queries similar to the one referenced here. In my scenario, there is a child element within a parent element (specifically a matSelect within a matCard, although that detail may not be significant) where the parent element has a set ...

Why doesn't package.json typically utilize the preset values stored in the .npmrc file?

Windows 10 x64 Based on the information found here, I created a file called C:\Users\bushm\.npmrc with the following content: author = "Andrey Bushman" However, when I run the command npm init -y in a new directory, I noticed that the pac ...

Encountering the error message "TypeError: Unable to access properties of null (reading 'get')" while utilizing useSearchParams within a Storybook file

Looking at the Next.js code in my component, I have the following: import { useSearchParams } from 'next/navigation'; const searchParams = useSearchParams(); const currentPage = parseInt(searchParams.get('page') || '', 10) || ...

Creating an external link in Angular with query parameters

I have created an app where users have their addresses listed, and I want to implement a feature that allows me to open Google Maps when clicking on the address. However, I am currently facing an issue where instead of getting the actual value of {{ this. ...

Packaging a NodeJS project in Visual Studio - A step-by-step guide to creating and setting up an N

In my VS2013 solution, I have a combination of NodeJS (using TypeScript) and C# class library projects connected by EdgeJS. Among the NodeJS projects, one serves as a library for a RabbitMQ bus implementation, while two are applications meant to be hosted ...

Utilize the up and down arrow keys to scroll through a description list in React

If you want to navigate through the list of Description Details using the tab and shift tab keys, it can be done easily. The default behavior allows for smooth navigation. <dl> <dt style={{ textAlign: "center" }}>Beast of Bodmin< ...