Error: Component with nested FormGroup does not have a valid value accessor for form control in Angular

In my setup, the parent component is utilizing a FormGroup and I am expecting the child components to notify any changes in value back to the parent. To achieve this, I am trying to implement NG_VALUE_ACCESSOR in the child component so that it can act like a form field. I believe that one needs to utilize the following 4 functions:

writeValue(value) {
    this.value = value;
}

registerOnChange(fn: any) {
    this.onChange = fn;
}

registerOnTouched(fn: any) {
    this.onTouch = fn;
}

setDisabledState?(isDisabled: boolean): void {
    this.isDisabled = isDisabled;
}

to make the child component behave like a form field. However, my current solution is not working as expected:

https://stackblitz.com/edit/angular-ivy-tpneik?file=src%2Fapp%2Fapp.component.ts

The error message I am currently encountering is:

Error: No value accessor for form control with path: 'ok -> isChecked'

My objective is to have a child component (and possibly more) that can accurately report its value changes to the parent form residing in the parent component. How should I go about addressing this issue?

Answer №1

Make sure to have a separate form within your child component and pass the nested formgroup to it for smooth functionality. This way, the parent will be aware of what's happening inside the child.

To pass the formgroup as a variable:

<div formGroupName="child">
  <app-form [formGroupChild]="formGroupChild" [myArray]="myArray"></app-form>
</div>

In the child component, receive the array and formgroup, use [formGroup] on a div element, and work your magic!

<div [formGroup]="formGroupChild">
  <div class="container">
    <div *ngFor="let category of myArray" [formGroupName]="category.id">
      <input type="checkbox" formControlName="isChecked">
      <div [style.color]="category.textColor">
        {{ category.name }}
      </div>
    </div>
  </div>
</div>

No need for controlvalueaccessor in this case :)

Your version on STACKBLITZ

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

Navigating routes for a module sourced from NPM: Best practices

Looking for guidance on loading Angular routes from an NPM module? Take a look at this snippet from my app.module.ts file: import { HelloWorldModule } from 'hello-world-app-npm/hello-world-app.umd.js'; // Loading module from NPM const routes = ...

Getting Started with Angular: Loading Data into a List from a Service

As I am relatively new to Angular, I have a list that needs to be displayed on the screen. Initially, I was able to show the list with hard-coded data, but now I need to fetch the data from my service that calls an API. The data retrieval part is already i ...

issue encountered when implementing slick.js in angular 6

Trying to implement slick.js, a carousel framework, in an Angular project. Initially attempted 'npm install slick --save' and manually adding the downloaded files to scripts and styles JSON objects. When that failed, resorted to importing the C ...

What method can be used to inherit the variable type of a class through its constructor

Currently, I am in the process of creating a validator class. Here's what it looks like: class Validator { private path: string; private data: unknown; constructor(path: string, data: string) { this.data = data; this.path = path; } ...

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

Modifying the interface state in React with TypeScript is not permitted

I encountered a compilation error in the code below, where I am unable to modify the state in closeLeftCol function. The error message states: Cannot assign to leftWidth because it is a constant or read only property: interface ILayoutState{ r ...

Encountering an issue with Angular 13 routing where extraction of property fails when returning value as an observable

After receiving an id number from the parent component, I pass it to my child component in order to retrieve a value with multiple properties. To achieve this, I created a service that returns an observable containing the desired object. However, when atte ...

Angular Observables do not update local variables when making API calls

For some reason, I cannot set a value in my local variable as expected. Here is the code snippet: export class memberComponent implements OnInit { member : Member = new Member(); constructor(private memberService: MemberService) {} ngOnInit() { ...

Error: Angular 4 encountered an unexpected character and could not parse

I am encountering an issue with a code snippet that looks like this: persona = { ... edadNiño = 9 } I'm trying to bind it using the following syntax: <input type="number" name="edadNiño" [(ngModel)] = "persona.edadNiño"> However, when I a ...

What is the best way to implement a custom layout with nuxt-property-decorator?

Summary of Different Header Components in Nuxt In order to set a different header component for a specific page in Nuxt, you can create separate layout files. layout ├ default.vue // <- common header └ custom.vue // <- special header for s ...

Combine the names of classes in an array into a union type

Can someone help me with extracting all the methods from an Array of Classes into one type Union? Here's an example: class A{ getBooks(): Book[]{} getBook(): Book{} } class B{ getUsers(): User[]{} getUser(): User{} getBooksOfUser(userId: s ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

Adonisjs latest version (v5) model creation command malfunctioning

Using Adonisjs v5 The controller command works fine with: node ace make:controller Posts However, the new model creation command is not working: node ace:make model Post When running the make model command, an error occurs: An error message stating &ap ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

What is the term for specifying a variable's data type using a set of values instead of a traditional type?

Recently, I stumbled upon some code that introduces a class with specific variables defined in an unconventional manner. export class Foo { id: string = "A regular string" bar: '>' | '<' | '=' | '<=' | ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

What impact does the deprecation of TSLint have on Angular projects?

At the company I currently work for, we are on the cusp of embarking on a new Angular application project. Delving into the topic of linting, I came across news that TSLint is in the process of being deprecated. Given that TSLint is integrated into Angula ...

Oops! There was an unexpected error in the authGuard: [object Object] was not caught as expected

I've been working on implementing authGuard in my app, but I keep encountering an error. Below is the guard implementation: canActivate(route: ActivatedRouteSnapshot): Observable<boolean> { /** * Returning an observable of type boolea ...

The significance of Import and Export in the Initialization of Angular's NgModule

I recently completed the Angular Tour Of Heroes tutorial and reached the router section. I came across this code snippet in the app-routing.module.ts file that left me puzzled: app-routing.module.ts file: @NgModule({ //Exporting the routermodule allo ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...