3

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?

3
  • Are you positive this is the site of your error? Here's a Stackblitz of this working in Angular 15. Commented Dec 12, 2022 at 17:06
  • If I dump everything in NgOnInit it works. I don't know what else could be causing the problem. Commented Dec 12, 2022 at 18:38
  • Direct instantiation now works for me: settingsForm = new FormBuilder().nonNullable.group({...}); - However, it is strange why it does not work DI and constructor. I couldn't reproduce the error either. Commented Dec 12, 2022 at 22:48

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting! Just strange that I can't get it reproduced with a new Angular 15 app and the problem only occurred when migrating my Angular 14 -> 15 App.. I rearranged my code and then leave it as it is. I'll still be happy to test your TS configuration later to see if it's the problem.
this kind of issue did occured to me in angular 19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.