0
votes

I have a use case where a parent component has two child components. When a child component is selected, the parents FormControl should be reset.

In order to do this, I need to send a boolean value from the children to the parent, but this is not functioning as expected.

Here is my current implementation - which is not working! Could someone explain what I am overlooking? Many thanks

Child component

Register the event emitter in the child

 @Output() formControlReset: EventEmitter<boolean> = new EventEmitter();

emit the event

this.formControlReset.emit(true);

Parent Component

<div>
     <input (formControlReset)="formControlReset($event)" [(ngModel)]="userInput" [formControl]="inputFormControl" *ngIf="showSearchInput" placeholder="Search here" #searchInput></input>
</div> 

call a reset on the formControl

formControlReset(value: boolean): void {
    console.log('doing something');
    this.inputFormControl.reset();
}
3
How are you calling the emitter? it won't work if you try testing it inside constructor. Try adding a button instead. <button (click)="onClick()">Click </button>. Then call it onClick(){this.formControlReset.emit(true);}Iancovici

3 Answers

0
votes

I see nothing wrong with what you posted.

@Input and @Output will only work when you have a parent-child component relationship, it will not work for unrelated component.

My guess is that the child component is not part of the parent component structure.

0
votes

It seems like you are not defining your child component using your child component's selector.

Change this:

<input (formControlReset)="formControlReset($event)" [(ngModel)]="userInput" [formControl]="inputFormControl" *ngIf="showSearchInput" placeholder="Search here" #searchInput></input>

To this:

<app-childSelector (formControlReset)="formControlReset($event)" [(ngModel)]="userInput" [formControl]="inputFormControl" *ngIf="showSearchInput" placeholder="Search here" #searchInput></app-childSelector>
0
votes

Folks have covered emitter, which should work fine if you have an actual parent-child component relationship. If these are sibling components instead, you'll need to pass data via a service.