Emit event from parent to child

后端 未结 2 1496
轻奢々
轻奢々 2020-11-28 08:29

I have a Submitbutton in the parent component namelypersonDetails.personDetailshas manyperson` components. Whenever I click on the Sub

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 08:58

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

提交回复
热议问题