Angular2 call method of other component

前端 未结 4 1802
故里飘歌
故里飘歌 2020-12-14 11:35

I have an Angular2 app in which I created an Header component, that\'s rendered in my main App component.

Now, I have an other Form component that should have its su

相关标签:
4条回答
  • Additionally to the solution with the Observable, I think it's important to say something about the EventEmitters as they are, in my opinion, easier to use in this kind of scenarios.

    In the child controller

    import the EventEmitter and the Output types.

    import { EventEmitter, Output } from "@angular/core

    declare an output property of type EventEmitter

    @Output() formSubmit$: EventEmitter<boolean>;

    remember to initialise the EventEmitter in the constructor as follows:

    this.formSubmit$ = new EventEmitter();

    and finally, with a proper action binded to the submit button, trigger the EventEmitter "emit" method to propagate the event across your app:

    this.formSubmit$.emit(true);

    In the parent Controller

    In the parent's view, bind the formSubmit$ event to an action of the controller:

    <child-selector (formSubmit$)="handleFormSubmit($event)"></child-selector>

    then declare the method in the Controller

    public handleFormSubmit(submit: boolean): void {
        alert("Form has been submitted! Do your stuff here!");
    }
    

    Obviously, this kind of strategy can be used only when you need to exchange data from a child to a parent controller.

    0 讨论(0)
  • 2020-12-14 12:10

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

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

    header.component.ts

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs/Subscription';
    
    import { CommonService } from './common.service';
    
    @Component({
      selector   : 'header',
      templateUrl : './header.html'
    })
    export class HeaderComponent implements OnInit, OnDestroy {
      constructor( private commonService: CommonService ){
      }
    
      ngOnInit() {       
      }
    
      onSubmit(){
        // this method needs to be called when user click on submit button from header
        this.commonService.notifyOther({option: 'onSubmit', value: 'From header'});
      }
    }
    

    form.component.ts

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs/Subscription';
    
    import { CommonService } from './common.service';
    
    @Component({
      selector   : 'form',
      templateUrl : './form.html'
    })
    export class FormComponent implements OnInit, OnDestroy {
      private subscription: Subscription;
      constructor( private commonService: CommonService ){
      }
    
      ngOnInit() {
        this.subscription = this.commonService.notifyObservable$.subscribe((res) => {
          if (res.hasOwnProperty('option') && res.option === 'onSubmit') {
            console.log(res.value);
            // perform your other action from here
    
          }
        });
      }
    
      ngOnDestroy() {
        this.subscription.unsubscribe();
      }
    }
    
    0 讨论(0)
  • 2020-12-14 12:13

    Parent and children communicate via a service

    Angular2 call method of other component

    0 讨论(0)
  • 2020-12-14 12:28

    The use of services and subjects is the easiest way. If you want to keep a record of your data, you can even use replay subject

    private notify: ReplaySubject<any> = new ReplaySubject<any>();
    

    But, you can even try out a library called as eventbus. I have ran into same issues and eventbus is just the right answer for this.

    0 讨论(0)
提交回复
热议问题