What is the best method for retrieving the complete path of a FormControl in Angular versions 4 and above

Is there a way to obtain the complete path of a FormControl in Angular 4+?

Below is my reactive form structure:

{
    name: '',
    address: {
        city: '',
        country: ''
    }
}

I urgently require the full path of the control:

const addressFormGroup = this.form.get('address');
const cityControl = addressFormGroup.get('city');
cityControl.plsGiveMeFullPath() // Should return 'address.city'

Are there any built-in methods to retrieve the full path of the cityControl: FormControl | FormGroup?

Answer №1

I have successfully implemented a pair of methods to achieve this specific functionality.

The initial method functions as a helper, tasked with retrieving the name of a control within its parent index. This is accomplished by scanning the parent's controls object for a matching control and then returning the corresponding key.

The second method operates recursively, leveraging the aforementioned helper to obtain the control's name and subsequently calling itself for the parent control. The returned strings are joined using dots ('.') along the way.

  getControlName(c: AbstractControl): string | null {
    if(!c.parent) return null;
    const formGroup = c.parent.controls;
    return Object.keys(formGroup).find(name => c === formGroup[name]) || null;
  }

  getControlPath(c: AbstractControl, path: string): string | null {
    path = this.getControlName(c) + path;

    if(c.parent && this.getControlName(c.parent)) {
      path = "."+path;
      return this.getControlPath(c.parent, path);
    } else {
      return path;
    }

  }

Answer №2

@sparrowrex Oh, this exceeds the character limit for a comment...

formGroup can be either AbstractControl[] or

{ [key: string]: AbstractControl }
. To handle both cases, simply check if it's an array and your code will function correctly:

const getControlName = (control: AbstractControl): string | null => {
  if (control.parent === null) {
    return null;
  }

  const children = control.parent.controls;

  if (Array.isArray(children)) {
    for (let index = 0; index < children.length; index++) {
      if (children[index] === control) {
        return `${index}`;
      }
    }
    return null;
  }

  return Object.keys(children).find(name => control === children[name]) || null;
};

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

Setting the date of the NgbDatePicker through code

I have implemented two NgbDatePicker components in my project: input( type="text", ngbDatepicker, #d="ngbDatepicker", [readonly]="true", formControlName='startDate', (dateSelect)='setNew ...

Exploring Angular2: Incorporating External Plugins with AngularCLI (webpack)

Currently, I am in the process of developing an Angular2 application using AngularCLI with webpack version. A third-party plugin called ScrollMagic is being utilized which comes with optional plugins of its own. The main codebase for ScrollMagic has been i ...

The function webpack.validateSchema does not exist

Out of the blue, Webpack has thrown this error: Error: webpack.validateSchema is not defined Everything was running smoothly on Friday, but today it's not working. No new changes have been made to the master branch since Friday. Tried pruning NPM ...

Using TypeScript to define task invocation parameters with AWS CDK's CfnMaintenanceWindowTask

Currently, I am utilizing AWS CDK along with the library @aws-cdk/aws-ssm and TypeScript to construct CfnMaintenanceWindowTask. The code example I am working on is derived from AWS CloudFormation documentation, specifically for "Create a Run Command t ...

Angular Error: Cannot call function panDelta on this.panZoomAPI

Check out my small demonstration using a stackblitz, I'm having an issue. In the setup, there's a master component with pan-zoom functionality containing a parent component with children content. The library in use is ngx-panzoom. The default c ...

Troubles with applying Global Themes in StyledComponents for React Native

Problem with Global Theme in StyledComponents (React Native) When attempting to utilize a color from my global theme in my component and setting it like so: background-color: ${({theme}) => theme.} The properties within theme, such as colors, font-siz ...

Tips for resetting a form after submission

Hey there, I'm currently working with Angular 7 and facing an issue with form submission. After submitting the form successfully, I want to reset it without triggering the required validation for input fields. Here's a snippet of my TypeScript co ...

How to assign a custom validator parameter to a form group in Angular

I'm in a situation where I have a form group and need to validate the end date so it is not earlier than the start date. The challenge here lies in accessing specific fields when the form group is not yet declared. dateFormGroup: this.fb.group({ ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

When running the test, a "is not defined" ReferenceError occurs in the declared namespace (.d.ts) in ts-jest

When running typescript with ts-jest, the application functions properly in the browser but encounters a ReferenceError: R is not defined error during testing. The directory structure: |--app | |--job.ts |--api | |--R.d.ts |--tests | |--job.test.ts ...

Understanding TypeScript's ability to infer types in generics

Exploring the world of TypeScript through a robustly typed system for REST requests. Let's dive into the code: This type is used to establish the connection between routes and their respective object types: export interface RoutesMapping { api1: ...

Learn the process of presenting data in an HTML file using TypeScript within AngularJS 8

I recently made a GET method API call in my app.component.ts file: export class UsersComponent implements OnInit { usersdatainfo : any; constructor( private http: HttpClient ) { this.http.get(this.url).subscribe( userdata => { ...

Guide to Display chat.html Overlay on home.html Using Ionic 2

In my Ionic project, I have two pages: home.html chat.html I am looking to display chat.html over home.html at the bottom right as a chat window. How can I accomplish this? I have attempted to illustrate what I envision in an image: ...

Encountering path import errors when developing a sample webpack site within a TypeScript library

Struggling to integrate my custom library with TypeScript and Webpack. Import errors are causing headaches, despite smooth sailing in CLion. Running tsc within the project directory is error-free, unlike when running npm run dev in the examples/webpack di ...

Paper-dropdown-menu component failing to render properly in web browser

Encountering an issue with the rendered HTML for a basic paper-dropdown-menu. Instead of displaying as a styled menu, the list items are just appearing as a plain list on the page. Upon clicking the rendered paper-input component within the dropdown, the ...

Different ways to separate an axios call into a distinct method with vuex and typescript

I have been working on organizing my code in Vuex actions to improve readability and efficiency. Specifically, I want to extract the axios call into its own method, but I haven't been successful so far. Below is a snippet of my code: async updateProf ...

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

Using TypeScript to define generic types for classes, method parameters, and method return types

I am facing an issue with this particular function function getCollection<T>(collectionType: T): Collection<T> { return new Collection<T>() } In the Collection class, I have the following code snippet export class Collection<T> { ...

Having trouble with Angular deeplinks - my app is opening but the routing isn't working as expected

Help needed: I'm facing an issue with deeplinks in my app where the routing is not working properly. Below is the code snippet causing the problem: import { Component, ViewChild } from ‘@angular/core’; import { App, Platform, Nav, NavController ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...