What is the most effective method for sharing a form across various components in Angular 5?

I have a primary form within a service named "MainService" (the actual form is much lengthier). Here is an overview-

export class MainService {

 this.mainForm = this.formBuilder.group({
            A: ['', Validators.required],
            B: '',
            C: '',
            D: this.formBuilder.array([]),
            E: this.formBuilder.array([]),
            F:'',
            G: this.formBuilder.array([]),
            H: this.formBuilder.array([]),
            I: this.formBuilder.array([]),
        });
    }
}

Various components access the form's values and modify the form by importing the service. The template appears like this-

<mat-form-field>
    <input matInput [formControl]="MainService.A">
    <mat-label></mat-label>
</mat-form-field>

Is this the most effective approach for sharing the form among different components? Each component corresponds to a distinct form control in the complete form, hence they need to refer to the same form.

For example, imagine a student filling out various details about an article they read (book title, number of pages, authors, topics, etc.). Each detail of the book serves as a form control within the main form, with each individual component responsible for updating a specific form control (e.g. one component managing the name input, another dealing with author information).

Thank you!

Answer №1

One effective method, in my view, is to develop a compact component that includes the form you want to share, and engage with it using @Input and @Output properties.

For instance, utilize the @Input to configure the initial state of the form, while employing the @Output to respond to form events (especially when utilizing reactive forms).

<my-shared-form
  [initialState]="{ control1: 'nice'}"
  (formValuesChanged)="doSomeThingWithValidForm($event)"
></my-shared-form>

Form component:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-shared-form',
  templateUrl: './my-shared-form.component.html',
  styleUrls: ['./my-shared-form.component.scss'],
})
export class MySharedFormComponent implements OnInit {
  @Input()
  public initialState: { [key: string]: any };

  @Output()
  public formValuesChanged = new EventEmitter<{ [key: string]: any }>();

  public form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      control1: [this.initialState.control1 ? this.initialState.control1 : ''],
    });

    this.form.valueChanges.subscribe((val) => {
      this.formValuesChanged.emit(val);
    });
  }
}

Form component template:

<form [formGroup]="form">
  <input type="text" formControlName="control1">
</form>

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

What is the best way to transfer information to a different NextJS page?

I want to implement a search input field. The idea is to allow the user to type something into the search bar and then send that input to another page where an API request will be made with the search content. Essentially, when the user types "something" ...

Session management functions properly in Postman, however, encountering issues when attempting to use it on a web

Working on a NodeJS project using express-session to handle sessions. When sending a post request to http://localhost:5500/login, a session is created with an additional property userid. Upon making a get request to http://localhost:5500/ using Postman, th ...

The issue arises when trying to use destructured imports with Mongoose

I've been developing a straightforward Express app with ES6. In the process of creating a schema and model for Mongoose, I encountered an issue with the following syntax: import mongoose, { Schema } from 'mongoose'; const PostSchema = new ...

Whenever I attempt to host my Node.js app using the GCP deploy command, it fails to work properly. The error message that appears states: "Module 'express' cannot be found."

My NodeJS application is written in TypeScript and utilizes the Express framework. I'm looking to host it on the GCP cloud using the gcloud app deploy command. First, I compile my TS sources to JavaScript - is this the correct approach? Afterwards, I ...

Improving the efficiency of calculating sliding window averages

I have a set of stock data that requires manipulation through various calculations. I have utilized numpy arrays for this purpose, which are considerably faster than Python's built-in functions. However, the execution time of my code is longer than an ...

Tips for converting a string array constant into a union type

I have a string array that I want to use to create a new type where the properties correspond to the elements in the array. There are different types of arrays and I have a function that generates different output types based on the input array. const RG ...

Angular 2 - Module 'ng-factory' not found

I am encountering an issue when trying to launch my clean UI theme using 'ng serve'. This is my first time working with Angular and I'm struggling to resolve this problem. Any assistance would be greatly appreciated. I have attempted re-inst ...

Guide on navigating through various HTML pages with distinct parameters using Node.js (Express server)

Seeking assistance with a Node.js server that receives an ID as a query parameter. Each time a client connects with different parameters, I aim to serve them a unique HTML page containing a simple UI with 2 dynamic arrays. Everything seems to be working co ...

How can we incorporate methods using TypeScript?

I'm currently diving into TypeScript and encountering some challenges when trying to incorporate new methods into the DOM or other pre-existing objects. For instance, I'm attempting to implement a method that can be utilized to display colored te ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...

JavaScript is unable to identify one of the JSON values

I am trying to extract the email field from a JSON file using JavaScript. Here is the snippet of code: "contacts": [ { "addedAt": 1332358711001, "vid": 1, "properties": { ...

Leveraging Emotion API in Video Content (JavaScript or Ruby)

Currently, I'm in the process of uploading a video to the Emotion API for videos, but unfortunately, I have not received any response yet. I managed to successfully upload it using the Microsoft online console. However, my attempts to integrate it in ...

What is the method to conceal a certain element in jQuery based on the value of another element?

I am dealing with the following HTML structure: <button id="hideToggle">show/hide</button> <form id="item"> <div>Item 1 <input name="item1" type="number"/></div> <div>Item 2 <input name="item2" type="nu ...

Transform React.js data from MySql into a variable

Hello there! I encountered an issue while working on coding my web app. **I am looking to execute this class only if the "swishes" value retrieved from a table in my MySQL database is greater than 0.** var thepos = 1; export default class W ...

I am facing difficulty in retrieving a unique dynamic div id using the useRef ReactJS hook, as it keeps returning the same id repeatedly

When using the useRef Reactjs hook, I encountered an issue where it returned the same id repeatedly instead of generating a dynamic div id. I need this functionality to map buttons and div ids in order to create a flexible accordion. The goal is to displ ...

React Native ScrollView with a custom footer that adjusts its size based on the content inside (

I've implemented the code below to ensure that the blue area in image 1 remains non-scrollable when there is sufficient space, but becomes scrollable when space is limited. However, I'm facing an issue where the ScrollView component is adding ext ...

What factors should be taken into account when allowing external websites to use scripts directly from your site?

My jQuery function searches the page for links to a specific domain, makes an ajax call to retrieve data, and creates a tooltip that appears when a visitor hovers over the link. It's similar to the functionality on wowhead.com/tooltips. When allowing ...

Stop jQuery popups from wrapping text when resizing the browser window

Whenever a link is clicked, a jQuery popup appears. The popup functions properly in terms of opening and closing, but I would like to ensure that its position remains fixed when resizing the browser window to avoid any wrapping issues. Typically, I use a ...

Annoying jQuery animation error: struggling to animate smoothly and revert back. Callback function conundrum?!

I'm completely lost with what I have accomplished. My goal was to create an animation where an element slides in from a certain position and then slides back when another element is clicked. To achieve this, I included the second event within the call ...

What is the method for generating a popover in HTML when a user hovers over a button?

In this scenario, I have implemented two status buttons with different colors. The green button corresponds to "RUNNING" and the red button indicates "TERMINATED", which are fetched from JASON data. Upon hovering over the green status button, the text "RU ...