Can you explain the distinction between the controls and get methods used with the FormGroup object?

I have encountered an interesting issue with 2 lines of code that essentially achieve the same outcome:

this.data.affiliateLinkUrl = this.bookLinkForm.controls['affiliateLinkUrl'].value;

this.data.affiliateLinkUrl = this.bookLinkForm.get('affiliateLinkUrl').value;

The second line, however, leads to a peculiar situation where a MatDialogRef object suddenly becomes undefined when the code is used right before calling a method on the MatDialogRef reference. Below is the relevant code snippet for context:

if(status.success){
    this.notificationService.notify('success','Success', status.info);
    this.data.title = this.bookLinkForm.controls['title'].value;
    this.data.content = this.bookLinkForm.controls['content'].value;
    this.data.affiliateLinkUrl = this.bookLinkForm.get('affiliateLinkUrl').value;
    this.dialogRef.close(this.data);
}

When 'get' is used to retrieve affiliateLinkUrl, the dialogRef inexplicably becomes undefined, whereas using the 'controls' method does not cause any issues. There are no evident errors in the code other than this unexpected behavior. The dialogRef object has been properly initialized in the constructor.

If anyone can shed light on what might be causing this discrepancy and explain the differences between the methods controls and get, I would greatly appreciate it.

Answer №1

Inquiring about the distinction between the methods controls and get?

Referencing the AbstractControl source code

  /**
   * Accesses a child control by its name or path.
   * @param path A string or array of string/number values defining the path to the control.
   * ### Accessing a nested control
   * Example: accessing a `name` control within a `person` sub-group:
   * * `this.form.get('person.name');`
   * -OR-
   * * `this.form.get(['person', 'name']);`
   */
  get(path: Array<string|number>|string): AbstractControl|null { return _find(this, path, '.'); }

Also, mentioned in the Angular.io doc on FormGroup:

constructor(controls: {
    [key: string]: AbstractControl;
}, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)

controls: A group of child controls registered under specific names.

The contrast should be clear now :)

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

The text field is being styled with inline styles automatically

I am trying to set a custom width for a textarea in my form, but the inline styles are automatically overriding my CSS. I have checked my scripts, but I am unsure which one is manipulating the DOM. If you have any insight, please let me know. This is the ...

When json.parse encounters an undefined value at position 1

Currently, I am diving into learning express.js and my latest project involves creating a web app that can convert cryptocurrency to Fiat currency. Things have been progressing smoothly so far, but I've hit a roadblock when attempting to use json.pars ...

Why are the UI components (`Card Number`, `MM/YY`, `CVC`) not being displayed in the React app when using Card

Having an issue where the CardElement Ui component is not visible in the image provided. It should appear above the Order Total: $0 next to the payment method. I've attempted various debugging methods without success. I'm still working on resolv ...

What is the most effective way to display a success notification?

After updating the data in my application, I want to display a success message. Although the Success function is functioning correctly, the message itself is not appearing. When I click on the save() button, a small alert box pops up but the message fails ...

Designing Buttons and Titles for the Login Page

I'm currently working on developing a straightforward login page in react native and I've encountered some difficulties with styling. Does anyone have tips on how to center the text on the button? Also, is there a way to move the INSTARIDE text ...

Executing a single command using Yargs triggers the execution of multiple other commands simultaneously

I've been diving into learning nodejs and yargs, and I decided to apply my knowledge by creating a command-line based note-taking app. The structure of my project involves two files: app.js and utils.js. When I run app.js, it imports the functions fr ...

Looking for a particular root node in a tree structure?

I am currently working on converting docx files to xml and using DOM to locate the parent node of a specific element. For instance <chapter> <title> <label>Chapter 1 </label> </title> ...

Guide to organizing elements in an array within a separate array

Our array consists of various items: const array = [object1, object2, ...] The structure of each item is defined as follows: type Item = { id: number; title: string contact: { id: number; name: string; }; project: { id: number; n ...

Tips for adding a bounding box to an image received from the server

I've got a python server that is returning a collection of bounding boxes post OCR processing (using Tesseract or similar). "bbox": [{ "x1": 223, "y1": 426, "x2": 1550, &q ...

Encountering a 502 (Bad Gateway) error when attempting to execute an operation hook in Loopback 3 with MongoDB

Let me outline the current scenario: At this point, I am dealing with a client application built on Angular 8/Ionic 4 that is making calls to an API (Loopback) using PATCH requests. The core of the issue lies in my approach of listening to the "after sav ...

Integrating a YouTube video in the Google Maps info window with the help of Ajax technology

Currently working on a project for Udacity, my goal is to develop a neighborhood map using Google Maps API alongside Knockout and Ajax to integrate with another 3rd party API. A unique aspect of my approach is focusing on bars in the neighborhood and utili ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

Automating the process of submitting a checkbox

Displayed below is a mix of HTML and JavaScript: <form method = "post" style="display: inline;" name="thisform<?php echo $employee->id; ?>"> <input type="hidden" name="user" value="<?php echo $employee->id; ?&g ...

Missing from the TypeScript compilation are Angular5's polyfills.ts and main.ts files

Here is the structure of my Angular5 project. https://i.stack.imgur.com/tmbE7.png Within both tsconfig.app.json and package.json, there is a common section: "include": [ "/src/main.ts", "/src/polyfills.ts" ] Despite trying various solu ...

Refreshing ng-model within a radio input

Currently, I am utilizing a jQuery library for radio/checkbox components. Although I am aware that combining jQuery with Angular is not ideal, the decision to use this particular library was out of my control and cannot be altered. One issue I have encount ...

Utilizing AngularJS scope within a modal viewport

I am encountering an issue with my simple controller while fetching and displaying messages using $http.get in HTML using ng-repeat. The problem arises when trying to access the messages from a modal window, as it always prints the first message only. ind ...

implementing dynamic navigation bar, when transforming into a dropdown menu using ReactJS

I am currently utilizing a navigation bar from a Bootstrap theme within my React project. The navigation bar includes an in-built media query that determines whether it should display as a dropdown menu or not, with a toggler to handle the dropdown functi ...

The date-picker element cannot be selected by html2canvas

I'm encountering an issue with Html2canvas while trying to capture a screenshot of my page. Specifically, the date shown in the date-picker on the page is not appearing in the screenshot. Do you have any insights into why this might be happening and h ...

Calculating the mean value of the numbers provided in the input

I'm struggling with calculating the average of numbers entered through a prompt window. I want to display the numbers as I've done so far, but combining them to find the average is proving difficult. Here's the code I have: <html> &l ...

What are the steps to modify the placeholder of the formik <Field/> component?

Struggling to figure out how to make the date input empty with Formik. I just want it to display nothing initially, but have been unable to do so after hours of trying different methods. <Field name="date" type="date" className ...