Angular 2如何将组件子组件中的方法发射到组件父类 [英] Angular 2 how to emit method in component child to component parent
本文介绍了Angular 2如何将组件子组件中的方法发射到组件父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从子组件中删除一个输入字段,它通过 @Output
信息传输,该信息将激活父组件中的方法 delete()
!
I tried to erase an input field from the child component, it is transferred by @Output
information that would activate a method delete()
in the parent component!
提前谢谢
推荐答案
您可以使用 EventEmitter
和 @Output
来完成:
在以下代码段中,您可以调用 passDataToParent()
函数以传递所需的数据.
In following snippet, you can call passDataToParent()
function to pass the desired data.
child.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child-component',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
// ******** Important part ******
@Output() emitter: EventEmitter<any[]> = new EventEmitter();
dataToEmit : any = "data to pass to parent component";
constructor() {}
ngOnInit() { }
//Call this function to pass data
passDataToParent() {
this.emitter.emit(this.dataToEmit);
}
}
parent.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from './child-component';
@Component({
selector: 'app-parent-component',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
// ******** Get reference of child component ******
@ViewChild(ChildComponent ) child : ChildComponent ;
constructor() {}
ngOnInit() { }
receiveDataFromChild(data) {
console.log(data);
}
}
最后在父HTML中
parent.component.html
<app-child (emitter)="receiveDataFromChild($event)"></app-child >
希望有帮助!
这篇关于Angular 2如何将组件子组件中的方法发射到组件父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文