Renê Silva Lima Renê Silva Lima -4 years ago 103
Javascript Question

Notify parent that there was a change on its child

I'm making a nested form with dynamic validation on Angular 2. I have a parent (

) which holds the nested forms and other properties and, there's the component
which is the nested form. Inside my nested form I have a checkbox that calls a function, this function change some inputs in my form. I want to know how I let the parent
realize that there were a change on the form.

This is the function that the checkbox call (this is inside

handleType(isJuridica: boolean, i:number): void {
let array = <FormArray> this.formDadosBancarios.get('dados_titular');
let cpf ="cpf");
let cnpj ='cnpj');
let data_nasc ='data_nasc');
const cpfCtrl = this.formDadosBancarios.get(['dados_titular',0,'cpf']);
const cnpjCtrl = this.formDadosBancarios.get(['dados_titular',0, 'cnpj']);
const data_nascCtrl = this.formDadosBancarios.get(['dados_titular',0,'data_nasc']);
const reqValidators: ValidatorFn[] = [Validators.required, Validators.pattern(this.cpf_REGEXP)];
if (isJuridica) {

So, this function set and remove validators from some inputs, the problem is that
never "realize it". How can I update it? I guess it has something with ngOnchages but I'm still very lost :(. Thanks

Answer Source

There are numerous ways you can notify a parent component of a change in a child component. One way for example, in your child component dadosTitularComponent you could implement an Output parameter that emits an updated value when the model changes:

@Output() modelChanged = new EventEmitter();

Then you can have the event emitter emit a value from the handleType function your checkbox calls with:


The someValue will be emitted through the Output variable modelChanged to the parent.

The parent component could listen for the modelChanged event with

<app-dadosTitularComponent (modelChanged)="someFunction($event)"></app-dadosTitularComponent>

Where someFunction is a function in the parent that can act on the changed model.

Hope that helps.

ngOnChanges is great for monitoring changes to Input properties on your child component, but that is monitoring changes sent from the parent into the child and not what you are wanting. You would set it up on your @Input() properties like this:

ngOnChanges(changes: SimpleChanges) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download