我可以在Angular 2中将事件从父母发送给孩子吗? [英] Can I emit the event from parent to child in Angular 2

查看:76
本文介绍了我可以在Angular 2中将事件从父母发送给孩子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在父类中提交了按钮,即 personDetails

I have submit button in the parent class namely personDetails.

personDetails 有许多人类。

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

Whenever I click on the submit button I want to call a method in child class.

如何使用输出?发布父/母方法?

How can I emit a method from parent to child using output?

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

Its easy to do from child to parent. I want to access the html value of the child component hence I need to emit an event from parent to child.

推荐答案

您可以创建一个在您的父母和子女组件之间共享的服务,您可以在其中定义 Observable ,以便您可以订阅该 Observable

You can create one service which is shared between your parent and child component in which you can define Observable so that you can subscribe to that Observable from child and perform some action when you receive some value from parent.

//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 @
$ b

//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

//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();
  }
}

这篇关于我可以在Angular 2中将事件从父母发送给孩子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆