Home > Software design >  Angular typed reactive form via FormBuilder in strict mode
Angular typed reactive form via FormBuilder in strict mode

Time:01-27

I'm trying to follow tutorial (Angular 15), buit it doesn't work https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c#file-01-ts

@Component({
  selector: 'login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {

   form = this.fb.group({
      email: ["", {
        validators: [Validators.required, Validators.email]
      }],
      password: ['', [Validators.required, Validators.minLength(8)]]
   });

  constructor(private fb: FormBuilder) {

  }

  login() {

  }
}

Throws

TypeError: Cannot read properties of undefined (reading 'group')

It seems the FormBuilder doesn't instantiate. I've tried to do it the "usual" way https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c#file-02-ts which works (I have to do form!: FormGroup though), but it's explicitely stated not to use this way, because then you lose form typing.

CodePudding user response:

The code you posted seems to work just fine. StackBlitz here

CodePudding user response:

You are likely to have in your tsconfig.json :

{
   target: "es2022",
   useDefineForClassFields: true
}

Disabling useDefineForClassFields will solve your problem !

  • Related