Is there a way to send a formGroup to a higher level component in Angular?

In my project, I am facing an issue with passing the formGroup from a child component to a parent component.

Here is how I attempted to solve this problem:

Child Component:

@Output() formGroup = new EventEmitter<Categoria>();

In my constructor and createFormGroup function:

constructor() {this.formGroup = createFormGroup()}

let createFormGroup = (dataItem?: CategoriaIcone) => {
    if (dataItem) {
        return new FormGroup({
        'NomeImagem': new FormControl(dataItem.NomeImagem), //name of the image
        'UrlImagemIcone': new FormControl(dataItem.UrlImagemIcone),
        'Imagem': new FormControl(''),
        'TypeImage': new FormControl('')
        });
    } else {
        return new FormGroup({
        'NomeImagem': new FormControl(''),
        'UrlImagemIcone': new FormControl(''),
        'Imagem': new FormControl(''),
        'TypeImage': new FormControl('')
        });
    }
}

However, I encountered an error in the constructor:

Type 'FormGroup' is missing the following properties from type 'EventEmitter': __isAsync, emit, subscribe, observers, and 17 more.

Answer №1

If you utilize the Suresh method along with ViewChild, it will operate smoothly. Example:

save(){
const formData = this.childComponent.getFormGroup();
// manipulate the form data
}

However, your main problem seems to be that you are assigning both the form and the emitter to the same variable. To rectify this:

1- Assign the emitter separately

@Output() emitter = new EventEmitter<Categoria>();

2- Trigger the emitter when you click save, for instance

clickSave(){
this.emitter.emit(this.formGroup)
}


Answer №2

To interact with a child component from its parent, you can use the following approach:

@ViewChild('childComp') childcomp: ChildComponent;

The child component should have a getter method that returns a formgroup instance.

Parent Component Example:

ngAfterViewInit(){
   this.childcomp.getFormGroup();
}

In Angular 8, you can access ViewChild elements inside ngOnInit and ngAfterViewInit by using static property.

Answer №3

Hey Meliondas, it seems like you may be a little confused about the purpose of @Output. The @Output decorator is used to mimic an event. For example, when we click on a div element, the event "click" is triggered and passed as an argument in the form of an object. In our code, we can handle this event as follows:

<div (click)="myfunction($event)">click</div>
//in .ts
myfunction(event)
{
     console.log(event)
}

Similarly, when dealing with child components, we follow the same pattern. In the parent component:

<app-child (myOutput)="myfunction($event)">click</app-child>
//in .ts
myfunction(event)
{
     console.log(event)
}

And in your child component:

@Output() myOutput = new EventEmitter<any>();
data = {name:'name', surname:'surname'};
this.myOutput.emit(data);

Therefore, in your parent component, the "event" is actually the object that you have emitted.

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

Tips for creating a click event for a ViewChild element reference in Angular 8

Having trouble getting the click event to work for an element reference in typescript. Can anyone provide guidance on how to properly write a click event for an element reference? app.component.ts: @ViewChild('testElem') el:ElementRef; @Vie ...

The error message TS2322 in MUI v5 states that the property 'fullWidth' is not found in the type 'IntrinsicAttributes & { theme: Theme; } & { children?: ReactNode; }'

As a user of MUI v5, I have implemented a straightforward FormControl as seen below. It is important to note that the property fullWidth is supported according to the official documentation. import React, { PropsWithChildren } from 'react' import ...

The problem of package related to scrolling header in Ionic arises when building with the `--prod` flag (Remember to include a @NgModule annotation

Hey there! I stumbled upon a package in the git repository that seems to have everything set up for compatibility with AOT. However, when attempting to build my app using the ionic build --prod command, the AOT build encounters an error as displayed below. ...

Struggling to Implement Foreign Key Constraint in NestJS One-to-Many Relationship using TypeORM

I am facing a challenge in establishing a one-to-many relationship between two entities (Token and User) within my NestJS application using TypeORM. Here is how I have defined the entities: For the Token entity: @Entity('tokens') export default ...

What is the correct location for storing .html, .css, and other files in a project involving Typescript, Angular 2, and ASP.Net Core 1.0?

When following a Typescript tutorial to create an ASP.Net Core application (with or without Angular 2), it is recommended to set up a folder called Scripts and use gulp tasks to selectively copy only the .js files to the wwwroot folder during the build pro ...

The Angular Material Stepper seems to have a glitch where calling the next() function does not work until I manually click

Currently, I am in the process of developing an Electron app using Angular 7 and Angular Material. Within my application, I have implemented a Stepper component where the second step involves making a call to the Electron main process to prompt the user t ...

Firing a function in Angular2 whenever an observable property undergoes a change

Utilizing a workingData service that stores crucial data across my application, it provides an observable to the Mock workingData object. @Injectable() export class WorkingDataService { getWorkingData(): Observable<WorkingData> { return Observ ...

Encountering an Issue in Angular 5: Trouble Retrieving Information from Local JSON Source [object Object]

Trying to fetch data from a file named sampledata.json Issues: {{sampledata}} is showing [object Object] {{sampleDataModel.Title}} is throwing an error: TypeError: Cannot read property 'Title' of undefined Contents of sampledata.json: { ...

There is no data in the $_POST array from the Http request in Angular or PHP

I've hit a roadblock with a straightforward problem, and despite my best efforts, I haven't been able to find a solution online. Here's the code that I'm struggling with: const URL = 'http://(...)/scripts/Fiabilisation_Unique.php& ...

Tips for releasing the "Angular and ASP.Net Core" template directly from Visual Studio 2022

I am currently in the process of deploying a sample .net8/Angular application that I have developed using the "Angular and ASP.Net Core" template available in Visual Studio 2022, from GitLab to a CloudFoundry server. However, it seems that there may be an ...

How come one child class in Angular does not update the value of another child class?

Having a challenge with typescript, here's the situation: An abstract parent class A. A child class B. A child class C. export abstract class BasePage { public value = 1; } @Component({...}) // selector, template ... export c ...

Tips on applying borders to dynamically generated content in jspdf autotable, similar to a template

Having trouble adding borders to my PDF generated using jsPDF autotable. I want the layout to match the template, can someone assist me in resolving this issue? I need the header border to consist of two lines, similar to the template image provided below ...

Experimenting with Cesium using Jasmine (Angular TypeScript)

I have a TypeScript app built using Angular that incorporates Cesium: cesium-container.component.ts import { Component, ElementRef } from '@angular/core'; import { Viewer } from 'cesium'; import { SomeOtherCesiumService } from 'sr ...

"Exploring ASP.NET 5 MVC6 Web API: Understanding how to handle Post requests with

Posting a JSON object in the body and binding it with [FromBody] or posting a header and binding it with [FromHeader(Name=...)] individually works fine. However, combining both methods does not seem to work. Is there a workaround or alternative way to bind ...

Using aliases for importing will not function in the Vite (React, Typescript) starter template

I had installed shadcn/ui into my vite boilerplate as per the documentation, but ran into issues with the compiler not recognizing the aliasing. I discovered that TypeScript utilizes multiple configuration files - tsconfig.json, tsconfig.app.json, and tsco ...

The Vue application is refusing to compile due to a syntax error caused by the presence of 'return' outside of a function

Upon attempting to run a build on my Vue app, I encountered the following syntax error. error in ./src/pages/Calendar.vue?vue&type=script&lang=ts& Syntax Error: 'return' outside of function. (175:4) 173 | getEventColor(event, Even ...

Redux Store Not Refreshing Quickly Enough

I am encountering a frustrating issue where my redux store does not seem to update in time due to what appears to be some kind of React preemptive optimization. Here's the code for my App component: // App component code here... Road Component // ...

Utilizing a variable name as an object key in TypeScript

Can this be achieved? static readonly statusMapping: { [key in UploadStatus]: PopupMessageStatus } = { UploadStatus.COMPLETED : PopupMessageStatus.COMPLETED } UploadStatus is an enum with numeric values, where UploadStatus.COMPLETED = 0 p ...

Mapping arguments as function values

Hello there, I have an array of objects that I am attempting to map through. const monthObject = { "March 2022": [ { "date": "2022-03-16", "amount": "-50", &q ...