0
votes

I have a parent component and a child component, I need to pass the formGroup from my child component to my parent component.

I tried it this way:

Child component:

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

My constructor/create formGroup function:

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

let createFormGroup = (dataItem?: CategoriaIcone) => {
    if (dataItem) {
        return new FormGroup({
        'NomeImagem': new FormControl(dataItem.NomeImagem), //nome da imagem
        '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('')
        });
    }
}

But I get an error in the constructor:

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

3

3 Answers

1
votes

You can use Suresh method with view child it will work like a charm. Example:

save(){
const formvalues = this.childcomp.getFormGroup();
// do somethimg with the form
}

But your issue , is mostly, you are setting the form and the emitter on the same variable, what you need to do is:

1- set the emitter

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

2- emit the form when you clic save for example

clicSave(){
this.emmitter.emit(this.formGroup)
}


0
votes

In Parent Component, You can access child component using

@ViewChild('childComp') childcomp: ChildComponent;

This child component needs to expose one getter method which will return formgroup instance.

Parent Component:

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

In Angular 8, using static property, you can access ViewChild Element inside ngOnInit, ngAfterViewInit.

0
votes

Meliondas, I think you're a bit confussed with @Output. @Output is to "simulate" an event. e.g. when we make a click on a div, we has the event "click" and as argument is an object. In code we have in the app:

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

Well, when we has a child component we make the same. In parent

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

And your children

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

So, in your parent the "event" is the object you emit