What is the method for accessing a validator that has been declared in a reactive form group while within the scope of a custom

Currently, I have a custom component that I am happy with and it is being used in a reactive form as shown below.

private init() {
  const control4 = new FormControl("yy", Validators.pattern(".{2}"));
  const control5 = new FormControl("zz", Validators.pattern(".{3}"));

  this.form = new FormGroup({
    c4: control4,
    c5: control5
  });
}

The error handling is done in the main component where I can access and display any errors. However, I want to add some functionality to the custom component so that it reacts when it is considered invalid.

<input id="c4" formControlName="c4">
<app-textbox formControlName="c5"></app-textbox>

One possible approach is to use the NG_VALIDATOR marker within the decorator of the app-textbox component and then reference it accordingly. Yet, this method will alter the existing validator setup in the main component as displayed above. After searching online for solutions, most results were about custom components and validators examples.

Is there a way to access the validator, the raised error, or even the regex used in the reactive form configuration from within the scope of the custom control that is being reacted to?

@Component({ selector: 'app-textbox', ... ,
  providers: [
    //{ provide: NG_VALIDATOR, useExisting: forwardRef(() => ...), multi: true }, 
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => ...), multi: true }]
})
export class TextboxComponent implements OnInit, ControlValueAccessor {
  ...
  private showMeTheStuff() {
    // access the validator, regex or error raised
  }
}

Answer №1

To achieve this functionality, utilize the injector along with the appropriate hooks. Begin by importing Injector and NgControl:

constructor(private injector: Injector) {}

ngAfterViewInit() {
  const ctrl = this.injector.get(NgControl, null)
  console.log(ctrl)
}

The 'ctrl' variable will represent the form control directive assigned to your custom control. This could be a form control name, a form control, or a form group. Explore these possibilities within the code and handle the relevant cases (ideally focusing on form control and form control name). You'll gain access to the control, its methods, properties, and any parent elements as well.

Alternatively, you can inject the ControlContainer:

constructor(private ctrl: ControlContainer) { }

Consider marking it as optional based on your requirements. This approach provides access to the parent form group directive, granting similar functionalities.

Answer №2

While it may not be the most ideal method, it still gets the job done:

If you wish to utilize the FormGroup within your custom component (child), simply pass the MainComponent's FormGroup (this.form) as an @Input to your custom component... This way, you will be able to access the complete FormGroup API using your variable.

For example:

<app-input [form]="form" formControlName="c5"></app-input>

Additionally, retrieve the MainComponent's form by adding @Input() form: FormGroup; in your child component (InputComponent).

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

Steps to align the outline of VS Code with the current location in the editor

When working in a language known for its large and complex files, it can be frustrating to navigate through the code. I often find myself scrolling up and down multiple times just to locate the current function name. This is why I am looking for a way to e ...

Docker brings up the login page, yet the node server.js for the MEAN stack isn't launching

Here's the latest configuration updates after adding a bounty: Configuration UPDATE: It seems that there is a CORS error occurring when trying to login, which is likely causing the problem. I've come across other posts, like this one, suggesting ...

Creating a custom Angular pipe to convert milliseconds to a formatted hh:mm:ss in Angular

Struggling to develop an Angular pipe that accurately converts milliseconds to hh:mm:ss format. Despite researching several articles, none of the solutions seem to work. Here is a snippet of the current pipe.ts implementation: transform(value) { le ...

Refreshing the Ionic page by reloading it after navigating to a different URL page

Currently, I am working on an Ionic app where users can edit and view their profiles. After making changes on the edit profile page, the app should automatically navigate to the view profile page. My current issue is that I need the view profile page to r ...

Angular only allows click events to trigger during a push

Is there a way to reveal the password without requiring a click, but simply by pushing on an eye icon? My code HTML <input [formControlName]="'password'" [type]="isShow ? 'text' : 'password'" class=&qu ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Restricting HTTP requests to once every 200 milliseconds in Angular 4 with filtering in place

In my current project, I am working on a page that utilizes an ngFor to display an array of objects. One of the features I want to implement is the ability for users to filter these objects by entering specific keywords in an input field. Since the data f ...

What methods does TypeScript use to verify primitive types during runtime?

Is it true that Typescript removes any type or interface at compile time? If so, how is it possible to determine an object's primitive type using the typeof keyword? Are custom interfaces handled differently than primitive types? const a = "strin ...

How to retrieve a value from a base64-decoded string in Angular 6?

I successfully decoded a Base64 string using the xml2js library and obtained the following XML value: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="293" height="102" viewBox="0 0 293 102" xmlns="http://www.w3.org/2000/svg" ...

Testing attributes and props with React Testing Library

Currently, I am in the process of developing a React application using TypeScript. For creating components, I rely on material-ui and for unit testing, I make use of react-testing-library. Specifically, I am working on designing a wrapper for the Grid com ...

Retrieving data through an Angular Material Table by employing an HTTP GET request

I am working with an Angular Material table and need to retrieve data from a service. Below is the code for the service. import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Message } from '../messag ...

Ways to customize the appearance of Angular material elements one by one?

I have a component that contains two Angular Material form components: <!-- First input --> <mat-form-field> <mat-label>Password</mat-label> <input matInput type="text"> </mat-form-field> <br&g ...

Utilize Sequelize's cascade feature within your application

I'm currently building a web application using sequelize and typescript. In my database, I have three tables: WfProjectObject, which is connected to WfProject, and WfStep, also linked to WfProject. My goal is to include WfStep when querying WfProject ...

Tips for creating dynamic amd-dependencies in TypeScript

Is there a way to dynamically load a Javascript language bundle file in Typescript based on the current language without using static methods? I want to avoid having to use comments like this for each bundle: /// <amd-dependency path="<path_to_bund ...

Unlocking the Secrets: Expert Methods to Obtain Assets through HttpClient in Angular

After researching similar inquiries, such as the response provided in this thread, it seems that downloading or reading files from the assets directory can be accomplished easily by utilizing the get method of the HttpClient. For instance, if I have a Down ...

Navigating an immutable list to make updates to its values

Within this list, I have an unalterable group of objects. My task is to change the value of the 'isReq' property to false for all objects except the one with the id 2. [ { 'id': 1, 'name': 'Ram', 'D ...

Troubleshooting mat-accordion title problem on mobile devices

Despite reading numerous blogs and conducting extensive searches on Google, I am still unable to resolve the CSS issue related to Angular material below. Your assistance in fixing this problem would be greatly appreciated. Desktop view: https://i.stack.im ...

Fundamentals of Angular 2

It's not just an inconvenience, but something that truly frustrates me. Could someone please clarify the following: Why does Angular load these scripts in HTML directly from node_modules https://i.sstatic.net/D8UrG.png Why am I unable to simply imp ...

Issues retrieving data using Ionic 4 native HTTP plugin result in returning an empty

Currently, I am working on an Ionic 4 project where I am attempting to retrieve a JSON array from a URL using the native HTTP for Ionic. However, when I attempt to fetch the data array from the URL in JSON format, I am met with an empty page. The JSON dat ...

Installation and execution of TypeScript jQuery / Bootstrap definition file on a local machine using npm typings: A step-by-step guide

Struggling to set up TypeScript jQuery and Bootstrap definition files in my new project using npm typings. Below are the steps I followed: 1- Open cmd, navigate to my project folder, and enter the following commands: npm install typings --global typings ...