Is it possible to pass a formgroup to the parent component?

Asked

Viewed 291 times

0

I have a parent component and a child component, I need to pass the formgroup of the child component to the parent component, I tried it that way:

Child element:

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

In the constructor I make an instance of that form group:

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 in the constructor:

Type 'Formgroup' is Missing the following properties from type 'Eventemitter': __isAsync, Emit, subscribe, Observers, and 17 more.

  • You created it as an eventEmitter and then re-assigned it to a formgroup, so the mistake.

2 answers

2


in that case it seems better to use viewChild.

@ViewChild('child') childComponent: childComponent;


submitForm(){
   console.log(childComponent.form);
}

1

Communication between components can be done either parent to child or inverse. However, from what I understand of your problem, the appropriate solution is through Viewchild.

But remember the component architecture analyze whether you really need the form fields in the parent component or only need the values of the fields. The idea of this thinking is to guarantee the principle of sole responsibility. The parent does not need to actually obtain the Formgroup, but the form value.

If you still need these values only when performing Submit through a button it is recommended to use @Output.

For both cases I leave an article to study the exchange of data between components: https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.