Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the controls and get methods of the FormGroup object?

I have 2 lines of code that pretty much do the same thing namely:

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


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

Yet the second causes a MatDialogRef object to suddenly become undefined when using this code right above where a method is called on the MatDialogRef reference. Heres the code snippet for reference:

      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 i get affiliateLinkUrl this way the dialogRef suddenly becomes undefined, when i use controls method instead everything is fine. There are no additional errors that can explain this. The dialogRef object is initialized in the constructor.

Can anyone tell me what might be causing this and what the difference is between the methods controls and get?

like image 313
Maurice Avatar asked Nov 26 '25 11:11

Maurice


1 Answers

According to your question 'what the difference is between the methods controls and get?'

From the AbstractControl source code

  /**
   * Retrieves a child control given the control's name or path.
   * @param path A dot-delimited string or array of string/number values that define the path to the
   * control.
   * ### Retrieve a nested control
   * For example, to get a `name` control nested 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, '.'); }

And from the Angular.io doc on FormGroup:

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

controls: A collection of child controls. The key for each child is the name under which it is registered.

I think the difference now is obvious :)

like image 174
shohrukh Avatar answered Nov 28 '25 23:11

shohrukh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!