Angular 2如何将组件子组件中的方法发射到组件父类

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 >

希望有帮助!