Incorporating FormControl Validators within a Child Component in Angular

Having two Angular Components, one is called parent.ts and the other is named child.ts.

Parent.ts contains a Form group, while child.ts passes the Form data via CVA to the parent.

Now, I am looking to create a reusable child component that can generate components like child1.ts, child2.ts, …

Everything has been working perfectly fine up until this point, where I have created multiple components in this manner.

The issue arises when some child components are required, whereas others are not.

When I provide Validators in the Parent component, validation works correctly as the form becomes invalid if fields are empty. However, the Child component does not receive the Validation state from parent.ts, which means it remains valid.

Consequently, the child component doesn't display the ng-error message.

My question is: How can I pass the Validation state from the parent to the child in order to display error messages?

Answer №1

To properly implement your CVA, follow this structure:


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

Additionally, ensure to eliminate the providers section from your @Component decorator.

By following these steps, you will gain access to:

this.ngControl.control.valid
this.ngControl.control.invalid
this.ngControl.control.pending
this.ngControl.control.status

This will allow you to monitor the state of your CVA in real-time.

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

Experience the dynamic live preview feature of Sanity integrated with NextJS 13

I am facing an issue with checking if preview mode is activated on my website. While following a YouTube tutorial, I realized that the instructions may be outdated with the latest NextJS update. This was the code snippet I was originally working with to ...

Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application. res=[ { "url": "/page1", "views": 2 }, { "url": "/page2", "views": 1 }, { "url": "/page1", "views": 10 }, { "url": "/page2", "views": 4 }, { "url": "/page3", "views": 1 }, ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

Error: In Angular Firebase, the type 'string' cannot be assigned to the type 'Date'

I am encountering an error. The following error is shown: "cannot read property 'toDate' of undefined. Without the toDate() | Date." After further investigation, I found: A Timestamp object with seconds=1545109200 and nanoseconds=0. A hel ...

Tips for resetting the mat-progress-spinner to its initial state

I want to use the spinner as a timer and switch the progress direction. Currently, it moves clockwise when going from 0 to 100, but I need it to go counterclockwise from 100 (equivalent to 15 minutes or 900 seconds) to 0 (when time runs out). <mat-prog ...

Tips for preventing HTTP calls within chained Angular subscriptionsHere are some strategies to prevent

I am faced with a scenario where I have to call an HTTP service to retrieve data, and then based on that data, I need to immediately make another HTTP request. Typically, I would use pipe along with switchMap to accomplish this task efficiently. However, t ...

What is the best method for showcasing this console.log information in an Angular application?

I have developed a feature that displays users who are online. While it works perfectly in the console log, I am struggling to show p as the result if the user is online. Below is the code snippet: ngOnInit() { this.socket.emit('online', { r ...

Badging with Angular, HTML, and Bootstrap

I've been attempting to integrate Bootstrap 5's badges into my Angular application, but they don't seem to be displaying correctly together. While using Angular 13, the html within the app-root component appears clustered without proper for ...

Unable to locate the term "module"

I've been working on a TypeScript file that includes an exported function called sum: This script is meant to be run in Node.js. function sum(a:number):number{ return a; } module.exports.sum=sum; I'm encountering some issues and I'm not ...

What sets apart `lib.es6.d.ts` from `lib.es2015.d.ts` in TypeScript?

I'm a bit confused about ES6 and ES2015. In TypeScript, there are two type declarations available for them: lib.es6.d.ts and lib.es2015.d.ts. Can someone explain the difference between these two? And which one is recommended to use? ...

PHP Authentication Validation for Usernames and Passwords

Currently, I am in the process of developing a login page where users input their username and password. This information is then cross-referenced with the database to confirm if they are valid credentials. If the two values match, the user will automatica ...

Issue: The formGroup function requires a valid FormGroup instance to be passed in. Data retrieval unsuccessful

My goal is to retrieve user data from a user method service in order to enable users to update their personal information, but I'm encountering an error. Currently, I can only access the "prenom" field, even though all the data is available as seen in ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Can you explain the significance of tslint's message: "Warning: The 'no-use-before-declare' rule necessitates type information"?

Can someone explain the significance of tslint's "no-use-before-declare" rule warning, which states that it requires type information? I've tried researching online but still don't fully understand its implications. ...

You are unable to define a module within an NgModule since it is not included in the current Angular compilation

Something strange is happening here as I am encountering an error message stating 'Cannot declare 'FormsModule' in an NgModule as it's not a part of the current compilation' when trying to import 'FormsModule' and 'R ...

The request to http://localhost:8000/api could not be completed due to a connection refusal error (

In the process of creating an Angular project aimed at displaying, adding, deleting, and updating employee details, I encountered persistent errors. Despite having my own API established with connections to Angular, Express, Node, and MongoDB, I continue f ...

Issues with eventEmitter functionality in Angular 2

Everyone performed admirably following the manual, here is the code snippet for WebSocketBroadcaster: import {EventEmitter, Injectable} from "@angular/core"; @Injectable() export class WebSocketBroadcaster { ee: EventEmitter<any> = new EventEmi ...

Struggling to make HttpClient Post work in Angular 5?

I'm facing an issue with my httpClient post request. The service is not throwing any errors, but it's also not successfully posting the data to the database. Below is the code snippet: dataService.ts import { Injectable } from '@angular/c ...

The modifications to the URL made by react-router-dom's 'useSearchParams' do not persist when adjusted through the onChange callback of the mui 'Tabs' component

One feature I am looking to implement is a tab navigation component that changes based on a specific search parameter called tab. For instance, if my URL reads as example.com?tab=test2, I want the navigation bar to highlight the item labeled test2. To ac ...

Enabling external POST requests on Angular 4 with asp.net MVC

We are facing a challenge with our Angular 4 app that uses asp.net mvc. The issue arises when an external site, specifically the DIBS payment portal, attempts to redirect back to our page using a POST method, resulting in a 404 not found error. Although th ...