简体   繁体   中英

Passing Data onChange from child to parent? Angular

I need to passing data from child to parent but on change.

Child component code:

  <input type="file" name="file" accept="image/*"
        (change)="handleInputChange($event)">

Parent component:

 <app-file-uploader></app-file-uploader>  //this is child component

I need pass ($event) to parent component.

You need to use Angular's Output() directive. This is how it's done:

First: In your child component, add the following import statement:

import { Output } from '@angular/core';

Second: In the child component class: add the following property:

@Output() onChange = new EventEmitter<any>();

Now in your handleInputChange($event) , you need to emit the onChange property:

handleInputChange($event){
    // ... all of your logic
    this.onChange.emit($event); // this will pass the $event object to the parent component.
}

Finally: In your parent component template, you can call your component like this:

<app-file-uploader (onChange)="callSomeFunction($event)"></app-file-uploader>

Note: replace callSomeFunction with whatever function you're calling.

Here's the Angular Documentation on how to use Output(). Hope this answer helps you!

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