Maurice
Maurice

Reputation: 7391

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?

Upvotes: 3

Views: 830

Answers (1)

shokha
shokha

Reputation: 3179

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 :)

Upvotes: 1

Related Questions