angularformgroups

Get Value of Angular FormGroup FormControls Methods


So, let's say you have a FormGroup built as such:

  let formGroup = new FormGroup({
    control1: new FormControl(null),
    control2: new FormControl('x'),
    control3: new FormControl(46)
  });

Now let's say we want to access the value of control2. I have seen this done multiple ways, but I have not been able to find much in the way of "best practices" or "preferred access methods". As examples, I have seen these methods used throughout a single application, even in a single component.

Method 1: formGroup.controls.control2.value

Method 2: formGroup.value.control2

Method 3: formGroup.get('control2').value

For the record, the only way I can recall seeing it used prior to this application is formGroup.controls.control2.value so now I am trying to figure out the "best practice" for accessing these controls and their values.

Is this just simple redundancy where you can do the same thing in different ways? Or are there actual differences that need to be accounted for with each of these methods?


Solution

  • There is no difference in those methods regarding on how to get the value, the difference depends if you want to access a feature in the control or not (formGroup.get('control2') vs formGroup.value.control2), so yes is just simple redundancy.

    The redundancy exists because FormGroup and FormControl extends from AbstractControl, so both share the same abstract properties/methods (value, get ->AbstractControl, getRawValue...).

    As a recommendation, perhaps a common/utility class could help you to avoid having multiple access methods to the same thing, the following example could help you, feel free to improve it as you wish.

    class Test {
      test() {
        const formGroup = new FormGroup({
          control1: new FormControl(null),
          control2: new FormControl('x'),
          control3: new FormControl(46)
        });
    
        const value = this.getFormValue(formGroup, 'control1');
        console.log(value);
      }
    
      public getFormValue<GroupT extends {[K in keyof GroupT]: AbstractControl}>(
        form: FormGroup<GroupT>,
        name: keyof GroupT,
        options?: {useRaw?: boolean; value?: string}
      ): string {
        const {useRaw, value} = options || {raw: false, value: ''};
        const control = form.get(name as string);
        const result = useRaw ? control?.getRawValue() : control?.value;
        return result || value || '';
      }
    }