What is the most efficient method for transferring a formGroup to a mat-step component?

Exploring the functionality of the angular-material stepper component with reactive forms has raised questions about the best architectural approach to allow each mat-step to access a unique formGroup.

In reviewing two examples, it appears that creating formGroup1 and formGroup2 outside of the stepper (as in example 1) is the simplest solution. However, the concern arises within each <form>, where I aim to have only one custom component containing its own

formGroup</code without involving the stepper container in managing the <code>formGroups
. Is there an alternative method to achieve this?

<parent that declares formGroup1>
    <mat-vertical-stepper linear>
      <mat-step [stepControl]="formGroup1">
        <form [formGroup]="formGroup1">
            <component that uses formGroup1></component>
        </form>
      </mat-step>
    <<mat-vertical-stepper>
</parent>

<parent oblivious to formGroup2>
    <mat-vertical-stepper linear>
        <mat-step [stepControl]="formGroup2">
            <form [formGroup]="formGroup2">
                <component declaring formGroup2></component>
            </form>
         </mat-step>
    </mat-vertical-stepper>
</parent>

Possible solutions contemplated:

  • Declare all formGroups in the parent component of the stepper and pass them down to child components (con: burdensome for the parent and complicates code comprehension)
  • Have each child component declare its formGroup and emit it to the parent using @Output(). Employ a FormArray in the parent component to remain unaware of child logic (con: requires indexing or identification to ensure correct form placement)
  • Utilize a single form in the parent encompassing the entire stepper process

An optimal solution to this problem is sought after as it seems like a crucial aspect may be overlooked.

Answer №1

In our application, I encountered a similar issue and opted for the @Output() method. It may not be the optimal solution, but it served its purpose effectively.

Parent Component HTML

<mat-step
        [stepControl]="form1"
        label="Step1"
        [completed]="form1?.valid">
      <app-step-one [(form)]="form1"></app-step-one>
    </mat-step>

Parent Component TypeScript

form1: FormGroup;

Child Component HTML

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

Child Component - You can extend this to every step from a parent class

  _form: FormGroup;

  @Input()
  get form() {
    return this._form;
  }

  @Output()
  formChange = new EventEmitter();
  set form(value) {
    this._form = value;
    this.formChange.emit(this._form);
  }

  ngOnInit() {
    this.form = this.fb.group({
      item: new FormControl('', Validators.required),
    });
  }

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

Connecting ViewChild to several elements

I have implemented a feature where I am displaying tabular data in DataTable for Angular. Within this, there is a button that triggers a click event. Upon clicking the button, a slide menu is displayed, which then triggers a modal open. To achieve this fun ...

Exploring the Power of Observable Arrays in Angular 2

I am working with the code snippet below: get items():Observable<MenuItem[]>{ let items: MenuItem[] = [ { label: "incidents_dialog_tab_actions_measures_defined" }, { label: "incidents_dialog_tab_actions_measure ...

React Form Hook: restoring uniform width to selectors once more

Looking to create a form using React form hooks and Material UI? Check out this link to codesandbox to see the code in action. In the CreateEmployee.tsx file under components\execute folder, you'll find the necessary code. There's also a UI ...

ngx: navigate to the specified URL once the user has been successfully logged in

I am faced with a dilemma where I must wait for my authentication server to return my token before calling my APIs. I am looking for a solution to ensure that my authState.token is not null before dispatching LoadMyStuffFromApi. I have implemented two res ...

Executing an AngularJS function using regular JavaScript code

I am currently working with AngularJS and Typescript. I have integrated an external library into my project and now I need to call an AngularJS method from that library, which is written in vanilla JavaScript. I tried following this example, but unfortunat ...

Error encountered with react-query and UseQueryResult due to incorrect data type

I'm currently implementing react-query in my TypeScript project: useOrderItemsForCardsInList.ts: import { getToken } from '../../tokens/getToken'; import { basePath } from '../../config/basePath'; import { getTokenAuthHeaders } fr ...

Having trouble accessing functions within the webpack bundle

As someone new to the world of JS library development, I have embarked on a journey to achieve the following goals: Creating a library with TypeScript Generating a bundle using webpack5 Publishing the library to npm Utilizing the library in other projects ...

Issue arising from swiper version 8 compatibility with angular version 16

After upgrading my Angular application to version 16 and implementing swiper version 8, I encountered errors when running the build:ssr command. The specific error message I received was: ./src/app/modules/pages/enterprise-price-list/enterprise-price-list. ...

What is the best way to ensure that Feature effects are fully registered before a component in the root module dispatches an action?

Within my lazy-loaded module (config.module.ts), I am using EffectsModule.forFeature([..., abcEffects, ...]), while in my bootstrap app module (app.module.ts) I have EffectsModule.forRoot([]). When my app.component is initialized, I trigger an action (whi ...

Is there a way to access configurations from a module import in NestJS?

If my module is defined as shown below: @Module({ imports: [ PassportModule.register({ defaultStrategy: 'jwt' }), JwtModule.register({ // Use ConfigService here secretOrPrivateKey: 'secretKey', signOptions: ...

Tips for transferring data to a child component's @Input using Observables

I've created an angular component that serves as a tab within a for loop on my HTML page: ... <ng-container *ngFor="let tabData of data$ | async;"> <tab-component id="{{ tabData.id }}" name="{{ tabData.name }} ...

Exploring the Incorporation of String as a Component Identifier in React and TypeScript

My input component can render either a textarea component (from a library) or a regular input. Check out the code below: import React, { useEffect, useRef, useState } from 'react' import './AppInput.css' interface Props { placehold ...

The main path is not being detected

I am facing an issue where one of the routes is failing silently with a 404 error. app.ts import * as express from 'express'; import * as rateLimit from 'express-rate-limit'; import * as helmet from 'helmet'; import * as xss ...

Angular makes it easy to extract multiple parameters from a URL

In the process of developing a basic Angular application using TypeScript, I have encountered an issue. Within my project, there is a URL structure like this: www.example.com/api/1/countries/Italy/ My goal is to extract the values 1 and Italy from this U ...

tips on how to shade a column in the material data table according to a specific condition when the table is first loaded

Is there a way to automatically highlight certain rows in the angular material data table based on specific column values when the table loads? Let's take a look at an example component below: @Component({ selector: 'table-basic-example', ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

How can you determine the type of an argument based on the type of another argument?

Is it possible to dynamically assign value types in the const set = (key: keyof Store, value: any) function based on the keys defined in the Store interface? For instance, setting a key foo as type number and key bar as type string[]. import store from & ...

A pair of rolling windows

I have a project similar to this one: http://codepen.io/dmastag/pen/oXORpZ However, I have added tabs (md-tabs) to the window on the right so that clicking switches between windows with their own scrolls. The problem is, I can't use the scroll funct ...

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

What's the best way to process a string array using iteration in Typescript?

I have an array of colors: colors = ['red','blue','purple']; I would like to display the following message: colors in ('red','blue','purple') When I tried to achieve this using forEach metho ...