简体   繁体   中英

Angular 2 - send data from Child to Parent component

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();
}

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.

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM