问题描述
我需要将数据从孩子传递到父母,但要进行更改。
子组件代码:
<input type="file" name="file" accept="image/*"
(change)="handleInputChange($event)">
父组件:
<app-file-uploader></app-file-uploader> //this is child component
我需要将($ event)传递给父组件。
解决方法
您需要使用Angular的Output()
指令。就是这样的:
首先:在您的子组件中,添加以下导入语句:
import { Output } from '@angular/core';
第二个:在子组件类中:添加以下属性:
@Output() onChange = new EventEmitter<any>();
现在,在您的handleInputChange($event)
中,您需要发出onChange属性:
handleInputChange($event){
// ... all of your logic
this.onChange.emit($event); // this will pass the $event object to the parent component.
}
最后::在父组件模板中,您可以像这样调用组件:
<app-file-uploader (onChange)="callSomeFunction($event)"></app-file-uploader>
注意:将callSomeFunction
替换为您要调用的任何函数。
有关如何使用Output()的信息,这里是Angular Documentation。希望这个答案对您有帮助!