2017-07-25 72 views
0

我嘗試從子組件刪除輸入字段,它是由@Ouput信息傳遞,將激活的方法刪除()在父組件!角2如何在組件子發出了Methode以組件父

預先感謝您

+3

你可以找到例如[文件]中(https://stackoverflow.com/documentation/angular/10836/sharing-data-among-components/32497/sending-data-from-child-to-parent-via -output-event-emitter#t = 201707251354497555945) – Nehal

回答

0

可以acomplish,使用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 > 

希望它能幫助!

+0

thk you !!但我已經開始閱讀這本書了! ^^ thck爲你提供幫助 –

0

使用eventEmitter。在這裏,我刪除了所選項目的值,但您可以刪除項目。對於異步渲染問題,你可以使用輸出EventEmitter和true。

I made example here

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

    @Input() sorting: string; 

    @Output() selectedItemChange = new EventEmitter<any>(true);