Home > Mobile >  Cannot invoke an object which is possibly 'undefined' - Optional chaining not removing err
Cannot invoke an object which is possibly 'undefined' - Optional chaining not removing err

Time:12-11

Trying to implement a custom formcontrol. I have strict mode set to true and do not want to remove it. Implementing the control value accessor functions all work with optional chaining, except setDisabledState. Even doing an implicit check for value being possibly undefined does not fix the issue.

Relevant code:

@ViewChild(FormControlDirective, {static: true}) formControlDirective!: FormControlDirective;
@Input() formControl!: FormControl | AbstractControl;

@Input()
formControlName!: string;
get control(): FormControl {
  return (this.formControl || this.controlContainer?.control?.get(this.formControlName)) as FormControl;
}

constructor(private controlContainer: ControlContainer) { }

// .... more code

// ISSUE BELOW!!!
setDisabledState(isDisabled: boolean): void {
  if (this.formControlDirective && this.formControlDirective.valueAccessor) {
    this.formControlDirective.valueAccessor.setDisabledState(isDisabled);
  }
}

Error being:

Cannot invoke an object which is possibly 'undefined'.

I reproduced the issue in this STACKBLITZ Note, disabling strict mode resolves the issue and code works as intended.

CodePudding user response:

setDisabledState is an optional property in the ControlValueAccessor interface: https://angular.io/api/forms/ControlValueAccessor

Therefore, it might not be a function.

You can add optional chaining to the method call too, which should fix your error:

this.formControlDirective?.valueAccessor?.setDisabledState?.(isDisabled);
  • Related