Diego
Diego

Reputation: 2360

Angular 18 FormBuilder error Property not initialized

I am doing a Dummy in Angular 18, I am using Reactive Forms and I an trying to implement FormBuilder

I have this constructor in my .ts

constructor(private builder:FormBuilder){
  
  }

Then I try to create the form with the validations.

 registerform= this.builder.group({
   username:this.builder.control('',Validators.required),
   name:this.builder.control('',Validators.compose([Validators.minLength(5),Validators.required])),
   email:this.builder.control('', Validators.compose([Validators.email,Validators.required])),

  });

But I got an error... saying

Property 'builder' is used before initialization

The html has his header.

<form class="example-form" [formGroup]="registerform" (ngSubmit)="ProceedRegister()">

I saw others examples that do not throw any errors.

How can I initialized this property?

Thanks

Upvotes: 1

Views: 263

Answers (3)

Naren Murali
Naren Murali

Reputation: 56054

You can also use inject and define the builder above the form initialisation and solve the issue. So you define builder before actually using it.

export class SomeComponent {
  builder = inject(FormBuilder);
  registerform= this.builder.group({
   username:this.builder.control('',Validators.required),
   name:this.builder.control('',Validators.compose([Validators.minLength(5),Validators.required])),
   email:this.builder.control('', Validators.compose([Validators.email,Validators.required])),
  });
  ...
}

Upvotes: 2

MGX
MGX

Reputation: 3521

By default in ES2022 the property useDefineForClassFields is set to true.

In the compiler options of tsconfig.json, set it to false, and you should not get the error anymore.

Upvotes: 1

Mateus Oliveira
Mateus Oliveira

Reputation: 99

you are going in the right way! But without the complete code, it's hard to help you in this case. The possibles issue, it's because your registerform is being initialized before your builder.

I've made this example for you. Try it your-self, follow the code structure, and everthing will work, I hope it can help you.

Exemple: StackBlitz

Upvotes: 0

Related Questions