0

I have a small project with a parent component and a child component. In my parent component I have a formArray in which I need to filter the correct formGroup to pass to child

EXAMPLE: (Parent Component)

<child-component [formGroup]="relevantForm"></child-component>

TypeScript:

   ngOnInit{
    setRelevantForm(id){
     this.relevantForm = this.formArray.controls.find(fa => fd.value.id === id);
    }
}

(Child Component) TypeScript:

constructor(private controlContainer: ControlContainer)

this.relevantForm = this.controlContainer.control

Now on my project I have a button to delete current relevantForm and after deletion setRelevantForm(id) runs again and sets current formGroup, however in child component I would like to get notified on this change in order to update view.

I know there are different ways to achive like passing form in @Input() like:

    <child-component [relevantForm]="relevantForm"></child-component>
     and in typeScript:

    @Input() relevantForm;

however, I do not know what is the right way to do so. is there any possible way to know if the form has changed in child component using controlContainer?

in another words. I want to know when the actual form has changed and not values on its formControls.

hope my questions is clear. thanks.

1 Answer 1

1

You can use FormGroupDirective to inject the form in all children components.
Note that this directive will inject the form only if child-component is inside the form tags

parent

<form [formGroup]="myForm>
    <child-component></child-component
</form

child

constructor(private formGroupDirective: FormGroupDirective)

// Original form injected into the child
this.relevantForm = this.formGroupContainer.control
// To observe changes in the form
this.onFormChange = this.relevantForm.valueChanges
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.