2017-07-09 1 views
2

の作業が、ここには作業 ではないではないが、子コンポーネント角度@outputが@outputのイベント・エミッターと親通信に子をやろうとし

import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core'; 

@Component({ 
    selector: 'app-emiter', 
    templateUrl: './emiter.component.html', 
    styleUrls: ['./emiter.component.css'] 
}) 
export class EmiterComponent implements OnInit { 

@Output() emitor: EventEmitter<any> 
    constructor() { this.emitor = new EventEmitter()} 

    touchHere(){this.emitor.emit('Should Work'); 
    console.log('<><><><>',this.emitor) // this comes empty 
    } 

    ngOnInit() { 
    } 

} 

あり、これはHTMLテンプレート

<p> 
<button (click)=" touchHere()" class="btn btn-success btn-block">touch</button> 
</p> 

ですconsole.logはtouch内に何も表示されません これを親コンポーネントの中に入れても何も表示されません 親コンポーネント

親テンプレート@outputで

<app-emitor>(emitor)='touchThis($event)'</app-emiter> 

が 'いわゆる' しなければならない、ない子法:ここ

import { Component , OnInit} from '@angular/core'; 
// service I use for other stuff// 
    import { SenderService } from './sender.service'; 
// I dont know if I have to import this but did it just in case 
    import { EmiterComponent } from './emiter/emiter.component' 

@Component({ 
     selector: 'app-root', 
     templateUrl: './app.component.html', 
     styleUrls: ['./app.component.css'] 
    }) 
    export class AppComponent { 
     title = 'app'; 
     user: any; 
     touchThis(message: string) { 
     console.log('Not working: ${message}'); 
     } 
     constructor(private mySessionService: SenderService) { } 
    } 

とは、HTMLテンプレートに

<div> 
    <app-emiter>(touchHere)='touchThis($event)'</app-emiter> 
</div> 

答えて

2

親コンポーネントテンプレートです。また

、以下を参照してください。https://angular.io/guide/component-interaction#parent-listens-for-child-event

+0

@Output decoratorは、子がイベントを送出するため、子にあります。そのイベントはconsole.loggedにする必要がありますが、空になっています。親では、イベントを受け取るイベントハンドラを置くが、子ではconsole.logのときに何かが見えるはずです – shark6552

+0

もちろん@Outputは子コンポーネントにあり、親テンプレートで呼び出す必要があります。あなたのコードでは、代わりに子メソッド(touchHere)を呼び出しています – Vega

+0

これは親テンプレートです

(touchHere)='touchThis($event)'
親コンポーネントにあるセレクタの内側にあるtouchHereを呼び出しています。しかし、いずれにしても、もし私が何かを見なければならない子供のconsole.logなら、私はそうではありません – shark6552

0
<app-emiter (emitor)="touchThis($event)" ></app-emiter> 

@Output()を使用することにより、あなたはディレクティブに変数の名前をcomponent.Addingエミッタのディレクティブで放出する必要があるとが、放出されたイベントを適用する必要がありますを渡す見積もり内のオーバーオーバー機能。