Home > Blockchain >  Angular 15 - FormsBuilder - TypeError: Cannot read properties of undefined (reading 'group'
Angular 15 - FormsBuilder - TypeError: Cannot read properties of undefined (reading 'group'

Time:12-17

I migrated my project to Angular 15 and can no longer directly use the FormsBuilder for Reactive Forms. I get an undefined exception:

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'group')
TypeError: Cannot read properties of undefined (reading 'group')

This is my code:

 settingsForm = this.formBuilder.group({
    locations: ''
  });

  constructor(private formBuilder: FormBuilder) {}

Everything worked fine before. A solution that works is via the lifecycle hook NgOnInit. However, that would be the non-recommended way and I lose my implicit typing.

What can be the reason?

CodePudding user response:

The reason for your issue is the tsconfig switch useDefineForClassFields.

When this is enabled, classes are initialized as defined in the ecma-standard, where the initialization order is a little different to typescript. See also the TS 3.7 release notes

So, when this is on, the field settingsForm is initialized before the constructor shorthands.

From my research I believe that this will be the default behaviour in future versions of typescript, so you should refactor your code accordingly.

// useDefineForClassFields = true
"use strict";
class Test {
    foo;
    bar = this.foo;
    constructor(foo) {
        this.foo = foo;
        console.log(this.foo, this.bar);
    }
}
const x = new Test('abc');
// useDefineForClassFields = false
"use strict";
class Test {
    constructor(foo) {
        this.foo = foo;
        this.bar = this.foo;
        console.log(this.foo, this.bar);
    }
}
const x = new Test('abc');

Generated on TS Playground

  • Related