我可以在Angular 2中将事件从父母发送给孩子吗?

我在父类中提交button,即personDetails

personDetails有许多人员类。

每当我点击提交button,我想调用子类中的方法。

我怎样才能发出一个方法从父母到孩子使用output

从小孩到家长很容易做到。 我想要访问子组件的html值,因此我需要从父到子发出一个事件。

您可以创build一个在父组件和子组件之间共享的服务,您可以在其中定义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(); } }