2016-09-28 44 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); 
}