Stefani Toto
Stefani Toto

Reputation: 290

How to initialize reactive form at service and than inject to component

How to initialize reactive form at service and than inject to each component?

I have 2 components and a service. Both components have same form becuse its just an exam to type at one component and display at other.

  -----service----


    
public form: FormGroup;

 constructor(
    private formBuilder: RxFormBuilder
  ) 

 createform(sfm) {
    this.form = this.formBuilder.formGroup(sfm);
  }






-------input and ouptu components --------



 constructor(
    private service: Service
  ) { }

  ngOnInit() {

    const sfm = new InputForm();
    this.service.createform(sfm);

}

This gives an error that form its not initialized.

Upvotes: 1

Views: 1891

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

Since your form is going to be leveraged by the Component it would make sense to return the generated form from the Service to the Component.

Your service should generate the Form based on some data too, so that your form could be initialized with some data.

That being said, return the form from the service method:

constructor(
  private formBuilder: FormBuilder
)

createForm(sfm) {
  return this.formBuilder.formGroup({
    /*Generate form based on sfm here*/
  });
}

Now you can call the createForm method in your Component and expect it to return a FormGroup:

userForm: FormGroup;

constructor(
  private service: Service
) {}

ngOnInit() {
  const initialData = {
    name: 'John'
  };
  this.userForm = this.service.createForm(initialData);
}

You can then use this form in the template as usual:

<form [formGroup]="userForm">
  ...
</form>

You might want to read through this article on AngularInDepth where I've done exactly that.

Upvotes: 3

Related Questions