Effective method of delegating a section of a reactive form to a child component in Angular 5

Here is a form declaration for reference:

    this.form = this.fb.group({
        party: this.fb.group({
            name: [null, Validators.required],
            givenName: [null, Validators.required],
            surname: [null, Validators.required],
            address: [""],
        }),
        role: this.fb.group({
            mobile: [""],
            landline: [""],
            email: [null, (c: AbstractControl) => {
                if (!c.value)
                    return null;
                return Validators.email(c);
            }],
        })
    });

The goal is to extract the party form group into a new component with its validation and HTML.

How can the this.form.party be initialized and passed into a child component responsible for creating the fields and validators?

export class PartyDetailsComponent implements OnInit {
    @Input group: FormGroup; // To be created in the parent component

    constructor(
        private readonly fb: FormBuilder,
        private readonly logger: NGXLogger
    ) {
    }

    ngOnInit() {
        // How should I correctly assign this to the parent `party`?
        this.fb.group({
            name: [null, Validators.required],
            givenName: [null, Validators.required],
            surname: [null, Validators.required],
            address: [""],
        });
    };
}

Answer №1

To achieve this, I employ the @Output method in the subordinate form component to trigger a change event.

By adopting this strategy, the party form becomes versatile and can operate independently or be combined with other forms seamlessly for enhanced reusability. Whether it's embedded in a modal window or placed on a webpage, the form adapts effortlessly.

Example:

<party-form [data]="someInitialValue" (onChange)="form.get('party').patchValue($event)"></party-form>

Implementation:

export class PartyFormComponent implements OnInit {
    @Output() onChange: EventEmitter<FormGroup> = new EventEmitter();

    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = fb.group({});

        // Trigger onChange event whenever form values change.
        this.form.valueChanges.subscribe(() => this.onChange.emit(this.form));
    }

    @Input()
    set data(data: Party) {
        if (data) {
            this.form.patchValue(data);
        }
    }

    ngOnInit() {
        // Emit the initial onChange event.
        this.onChange.emit(this.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

Angular5 causing all divs to have click events at once instead of individually triggered

I am a beginner when it comes to working with Angular and I have encountered an issue. I created a click event on a FAQ page in Angular 5, but the problem is that when I click on one FAQ, they all open up instead of just the targeted one. Here is my TypeS ...

How can I ensure that several components are correctly subscribing to an observable at the same time?

I am working on a client service that has a method: receiveData (params) { return this.http.get(url, { params: params }); } Then there is a service that utilizes this: getData () { return this.client.receiveData(this.params); } Later on, there is a c ...

React-Redux button unit test in Vitest encounters failure

I'm struggling with passing a button click test in my app component using Vitest, react-testing-library, and jest dom. As a newcomer to unit testing, I'm having difficulty figuring out how to make my test for the submit button in my form function ...

Forget it, Access Denied

Recently, I started using nvm to handle multiple node versions, but things took a turn for the worse when I attempted to install a wrong dependency on my Angular 5 application. Instead of ng2-redux, I accidentally installed ng-redux. Now, I'm faced w ...

An issue has been identified with React's HTML input maxLength feature where it does not display an error

Within my form, I have an input field that currently does not include validation for a maximum length. <input type="text" className="form-control" id="company" onBlur= ...

Click event for a tree component in Angular 2

How can I trigger a node click event in an Angular tree component? import { TREE_ACTIONS, KEYS, IActionMapping } from 'angular2-tree-component'; const actionMapping:IActionMapping = { mouse: { click: TREE_ACTIONS.TOGGLE_SELECTED_MULTI } ...

Execute environment validation on server during `next build` command

I have a src/config/server/ts file that contains the following code: 'use server'; import zod from 'zod'; if (typeof window !== 'undefined') { throw new Error('env should not be imported on the frontend!'); } co ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

Showing No Data Available in Angular 2

Is there a directive in Angular 2 that can help display "No data found" in a table when it's empty? Alternatively, can I create this functionality in my services when subscribing to fetched data? <table> <tbody> <tr *ngFo ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

The NX Monorepo housing a variety of applications with unique design themes all utilizing a single, comprehensive UI component

We are currently working on a design system for a NX monorepo that has the potential to host multiple apps (built using Next.js), all of which will share a common component library. While each app requires its own unique theme, the UI components in the lib ...

Discover the proper technique to display an error message in cases where no data is detected during the filtering process

I'm currently working on a component that involves search filtering and dropdown filtering. The filtering functionality is working fine, but I'm struggling to determine where to display an error message if no data is found during the filtering pr ...

Error in Angular2: Method this.http.post is invalid and cannot be executed

import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; // import 'rx ...

Ways to turn off specific ngtsc warnings

Ever since updating my Angular app to version 15, I've been noticing some warnings popping up in both the terminal and Chrome DevTools. Is there a way to turn off or disable these warnings? I keep seeing this warning message about the optional chain o ...

Typescript: Displaying two values as input (one being disregarded)

Is there a way to display both the name and id values in an input box that is set to readonly? <input readonly type="text" [value]="car.name"> I need to also show the car id. Any suggestions on how to achieve this? ...

TypeScript is throwing an error about a missing property, even though it has been defined

Within the PianoMK1Props component, there is a prop known as recording which accepts an object with specific properties. The structure of this object is defined like so(the state variable): const [recording, setRecording] = useState({ mode: "REC ...

Challenges arise when attempting to merge declarations in Typescript involving passport, passport-local, and express-session

I'm currently facing challenges trying to integrate passport, passport-local, and express-session with Typescript. After installing all four necessary libraries - @types/passport, @types/express-session @types/passport-local, and @types/express - I in ...

The ngbDatepicker within the Bootstrap angular framework is designed to seamlessly integrate with ngbPanelContent without causing overflow issues

I've integrated the ngbDatepicker into a form as shown below <ngb-panel> <ng-template ngbPanelTitle> <div class="row"> <ui-switch (change)="onChange($event,2)" [checked]="profession ...

Differences between Typescript and Node versions

Is there a connection between the version of Typescript and the version of Node since Typescript is a global npm module? In other words, is there a minimum Node version required to run a specific version of Typescript. ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...