Initiating a reactive form within a service and then injecting it into a component

How can I set up a reactive form in a service and then inject it into each component?

I have two components and a service. Both components share the same form as it is simply for typing in one component and displaying in the other.

  
// ---- Service Setup ----

public form: FormGroup;

constructor(
    private formBuilder: RxFormBuilder
) 

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

// ---- Input and Output Components Setup ----

constructor(
    private service: Service
) { }

ngOnInit() {

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

}

This results in an error stating that the form has not been initialized.

Answer №1

When working with a form that will be used by the Component, it is best to have the Service return the generated form to the Component.

The service should generate the form based on certain data, allowing the form to be pre-filled with that data.

To achieve this, simply return the form from the service method:

constructor(
  private formBuilder: FormBuilder
)

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

Now in your Component, you can call the createForm method and expect to receive 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>

For more insights into this approach, check out this article on AngularInDepth.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Angular4 and TypeScript Compile Error TS2453: A Comprehensive

I'm facing an issue in my Angular4 project build process which I find quite perplexing. The error seems to be related to the import of certain components such as Response, Headers, and Http from @angular. Whenever I attempt to build my project, it thr ...

Securing Your Angular 2 / ASP.NET MVC Application from CSRF Attacks

I am currently developing a single-page application using ASP.NET MVC for the backend and Angular 2 for the frontend. To prevent cross-site request forgery attacks in my application, I have implemented the following steps: Since ASP.NET MVC sends a co ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

PrimeNg element for showcasing incorrect user input similar to mat-error

Is there an equivalent of mat-error in PrimeNg like Angular Material? <mat-form-field appearance="fill"> <mat-label>Enter your email</mat-label> <input matInput placeholder="<a href="/cdn-cgi/l/email-protecti ...

Encountering an issue while attempting to load in Angular2 RC4: Error: XHR error (404 Not Found) during loading

I encountered an exception while the application was loading on the browser. Here are the details of the error along with the configuration files: Error Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:5 ...

When using TypeScript, the tls.TLSSocket() function may trigger an error mentioning the absence of a "socket" parameter

Currently, I am in the process of building a basic IRC bot and using raw sockets to connect to the IRC server. Initially written in plain Javascript, I am now transitioning it to TypeScript. However, I have encountered an unusual issue when attempting to c ...

Could someone provide some insights on how the ( !! ) operator functions?

Angular 6 has arrived and while browsing through a quick tutorial on Medium, I stumbled upon this interesting piece of code. else if (!!this.day4Name && !this.day5Name && days[date] !== this.day4Name) { this.day5Name = days[date]; ...

Sinon made it difficult to successfully stub/mock a method return

I find myself facing a challenge as I navigate the learning path to nodejs and explore advanced javascript features. Progress is slow but steady. One of the rest endpoints utilizes the (azure blob storage) method from containerclient, which requires conver ...

tinyMCE5 has a quirky habit of inserting p tags without warning, but only when using

My editor with tinymce5 works well on Chrome and other browsers, but in Mozilla Firefox each line in the editor gets an additional p tag. I am using it with Angular. Currently, I have initialized the editor like this: <editor name="resultEditor" ...

Sending Angular forms to various endpoints

On a page, I have a form consisting of three different groups this.form = this.formBuilder.group({ profile: this.formBuilder.group({ name: [''], description: [''], }), members: this.formBuilder.array([ this.formBu ...

Setting Up Absolute Imports in Node.js using TypeScript

I recently completed a project in Node using TypeScript, and I am currently experimenting with implementing absolute paths for imports. However, upon running the project, it starts to fail with the following error message: [1] Error: Cannot find module &a ...

Why is Angularfire2 failing to save the data it fetches?

It seems that I am struggling to accomplish what I need because of a lack of knowledge on the proper method. My goal is to save a connection between a user and a school (which is also a user), and then retrieve some image URLs from the school user in a new ...

How can I incorporate Scroll effects using Angular 8 and rxjs 6?

I currently have the template setup like this: <div id="top"> ... </div> Within my component, I've implemented the following method: onTripSave() { let top = document.getElementById('top'); if (top !== null) { to ...

How can a new component be added as a child of an element without replacing or interfering with other

Whenever I dynamically generate components and attach them as children to an element upon creation, everything within that element gets deleted. Here's an example: public fn(event) { // Create component factory const factory = this.componentF ...

Response type tailored to specific input type

I am working on defining types for a simple function called fun. Below are the interfaces for the input and response: interface Input { test1?: true test2?: true test3?: true } interface Res { test1?: string test2?: string test3?: string } N ...

Utilize string values as identifiers in type declarations

My Props type declaration currently looks like this: type Props<FormData> = { formData: FormData, sectionNme: keyof FormData, name: string } However, I am trying to modify it to look more like the following: type Props<FormData> = ...

Checking if a useState setter passed in props is triggered in a Jest test

In a React component, I have the following functions: const changeOrder => { a websocket request }; const handleArrow = async () => { const res = await changeOrder(side, headingOrder, config); if (res !== undefined) setOrder(res); }; The se ...

Concealing Table Rows in Angular Material - How can I make table rows visible only after they are searched

I'm relatively new to Angular and although I initially thought it would be straightforward, I am struggling to make my app work the way I intend. I have a search bar and a datatable utilizing Angular Material. My goal is to only display items in the t ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

The 'subscribe' attribute is not a part of the 'OperatorFunction<{},{>}' structure

Below is a snippet of code from my service file: import { Injectable } from '@angular/core'; import { Http, Response } from "@angular/http"; import {map, catchError} from 'rxjs/operators'; import { Observable } from "../../node_modules ...