2016-09-28 53 views
6

我已經在父類中提交了按鈕,即personDetails我可以在Angular 2中從父母到孩子發送事件

personDetails有許多人類。

每當我點擊提交按鈕,我想調用子類中的方法。

如何使用output從父母到孩子發出一種方法?

它很容易做到從小孩到家長。我想訪問子組件的html值,因此我需要從父到子發出一個事件。

回答

19

您可以創建一個在您的父母和子女組件之間共享的服務,您可以在其中定義Observable,以便您可以從子女訂閱Observable,並在您從父母收到某些值時執行某些操作。

//common.service.ts 

import { Injectable, Inject } from '@angular/core'; 
import { Subject } from 'rxjs/Subject'; 
@Injectable() 
export class CommonService { 
    private notify = new Subject<any>(); 
    /** 
    * Observable string streams 
    */ 
    notifyObservable$ = this.notify.asObservable(); 

    constructor(){} 

    public notifyOther(data: any) { 
    if (data) { 
     this.notify.next(data); 
    } 
    } 
} 

//parent.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { Subscription } from 'rxjs/Subscription'; 

import { CommonService } from './common.service'; 

@Component({ 
    selector : 'parent', 
    templateUrl : './parent.html' 
}) 
export class ParentComponent implements OnInit, OnDestroy { 
    constructor(private commonService: CommonService){ 
    } 

    ngOnInit() { 
    this.commonService.notifyOther({option: 'call_child', value: 'From child'}); 
    } 
} 

//child.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { Subscription } from 'rxjs/Subscription'; 

import { CommonService } from './common.service'; 

@Component({ 
    selector : 'child', 
    templateUrl : './child.html' 
}) 
export class ChildComponent implements OnInit, OnDestroy { 
    private subscription: Subscription; 
    constructor(private commonService: CommonService){ 
    } 

    ngOnInit() { 
    this.subscription = this.commonService.notifyObservable$.subscribe((res) => { 
     if (res.hasOwnProperty('option') && res.option === 'call_child') { 
     console.log(res.value); 
     // perform your other action from here 

     } 
    }); 
    } 

    ngOnDestroy() { 
    this.subscription.unsubscribe(); 
    } 
} 
+0

請通過這個鏈接... http://stackoverflow.com/questions/39717465/how-to-read-directive-model-value-in-它的主控制器使用angular2/39719175?noredirect = 1#comment66739597_39719175 ..在這裏我已經提到父母和孩子的組成部分。請告訴我如何訪問父級中的personDetails對象。或者我怎麼能在兒童中調用提交方法..這個問題是類似的這個鏈接 –

+0

如何從父母的HTML附加到事件的孩子..例如有一個提交按鈕在父母,當我點擊它如何可以在兒童。我可以使用submit()來代替ngOnInit()嗎? –

+0

當你點擊從父母提交,然後用一些參數調用commonService的notifyOther,並通過訂閱它並基於params的值調用你的孩子的行爲來檢查'child'中的params值。 – ranakrunal9

0

在childComponent.ts

@Input() private uploadSuccess: EventEmitter<boolean>; 

在ParentComponent.html

<app-gallery [uploadSuccess] = "uploadSuccess" > </app-gallery> 

在ParentComponent.ts

private uploadSuccess: EventEmitter<boolean> = new EventEmitter(); 

onImageUploadSuccess(event) { 
    console.log('Image Upload succes'); 
    if (event.code === 'OK' && this.maxUploadLimit > 0) { 
     this.galleryImagesCount = this.galleryImagesCount + 1; 
     this.maxUploadLimit = this.maxUploadLimit - 1; 
    } 
    this.uploadSuccess.emit(true); 
}