Angular 2如何在组件子组件父组件中发出方法

时间:2017-07-25 13:53:25

标签: angular

我尝试从子组件中删除输入字段,它通过@Output信息传输,这些信息将激活父组件中的方法delete()

提前谢谢

2 个答案:

答案 0 :(得分:6)

您可以使用EventEmitter@Output

来完成该操作

在以下代码段中,您可以调用passDataToParent()函数来传递所需的数据。

<强> 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 >

希望它有所帮助!

答案 1 :(得分:0)

使用eventEmitter。这里我删除了所选项目的值,但您可以删除项目。对于异步渲染问题,您可以使用带有true的输出EventEmitter。

I made example here

  @Input() items: any[];
  @Input() selectedItem: any;
  keys: string[] = [];

  @Input() sorting: string;

  @Output() selectedItemChange = new EventEmitter<any>(true);
相关问题