3

I have two different component - one component has click event method for the list users & I want to inherit(invoke) that click event method on detail page(another component) )

How to do that, Please help me...

ANSWER UPDATE

Thanks For your Answers.

I have got the solution by Using extend Class & using super() in constructor.

First Class

export class TeamsView {
   constructor(private test:TestService){
   }
   ...
}

Second Class

export class TeamsForm extends TeamsView {
   constructor(private test:TestService, private router: Router){
     super(test)
   }
   ...
}
Jignesh Vagh
  • 122
  • 1
  • 3
  • 18

6 Answers6

21

1. Invoking method from one component to another component (if they are not parent and child), can only be possible using services.

    //FirstComponent

    import {Component} from '@angular/core';
    import {CommonService} from './common.service';

    @Component({
      selector: '<first-component></first-component>',
      template: 'some html here',
      providers: [CommonService]
    })

    export class FirstComponent {
      constructor(private _service: CommonService) {
       this._service.callMethodOfSecondComponent(); 
      }

    }


    //CommonService

    import {Subject} from 'rxjs/Subject'; 

    @Injectable()
    export class CommonService {
      invokeEvent: Subject<any> = new Subject(); 

      callMethodOfSecondComponent() { 
        this.invokeEvent.next(someValue)      
      }
    }


     //SecondComponent

    import {Component, OnInit} from '@angular/core';
    import {CommonService} from './common.service';

    @Component({
      selector: '<second-component></second-component>',
      template: 'some html here',
      providers: [CommonService]
    })

    export class SecondComponent {
      constructor(private _service: CommonService) {
       this._service.invokeEvent.subscribe(value => {
        if(value === 'someVal'){
         this.callMyMethod(); 
       }
      }); 
      }

      callMyMethod(){
      //code block to run
      }
    }

2. Invoking method of parent component from child component

    //Child Component

    import {Component} from '@angular/core';
    @Component({
      selector: '<child-component></child-component>',
      template: 'some html here',
    })

    export class ChildComponent {
      @Output()
      emitFunctionOfParent: EventEmitter<any> = new EventEmitter<any>();
      constructor() {
      }

      someMethodOfChildComponent(){
       this.emitFunctionOfParent.emit(someValue); 
      }

    }

    //ParentComponent

    import {Component} from '@angular/core';
    @Component({
      selector: '<parent-component></parent-component>',
      template: `some html
                <child-component 
                (emitFunctionOfParent)="myMethod($event)">
                 </child-component>   
                 some html
                `,
    })

    export class ParentComponent {
      constructor() {
      }

      myMethod(someValue){
      // i am called
      }

    }

3. Invoking method of child component from parent component

//Child Component

    import {Component} from '@angular/core';
    @Component({
      selector: '<child-component></child-component>',
      template: 'some html here',
    })

    export class ChildComponent {

      constructor() {
      }

      someMethodOfChildComponentToBeCalled(){
       // i am called
      }

    }


//Parent Component

    import {Component, OnInit} from '@angular/core';
    import {ChildComponent} from './child.component';
    @Component({
      selector: '<parent-component></parent-component>',
       template: `some html
                <child-component>
                 </child-component>   
                 some html
                `
    })

    export class ParentComponent implements OnInit {
      @ViewChild(ChildComponent) private _child: 
      ChildComponent;

      ngOnInit() { 
      this._child.someMethodOfChildComponentToBeCalled();
      }



    }

There might be other ways for communication as well except these ones. :)

nirazlatu
  • 983
  • 8
  • 18
  • Thanks for #1 above, it was what I needed. However It wasn't working for me until I learned from Stack Overflow "subscribe angular2 not working" that my issue was the "providers: [CommonService]" providing the CommonService in multiple spots, separate instances of CommonService were being instantiated -- so it wasn't "common" after all. I eliminated the two "providers: [CommonService]" shown and instead provided CommonService in the one common app.module.ts for my app. (Also, best to capture the $subscription returned and do an .unsubscribe() in ngOnDestroy().) – StackOverflowUser Nov 28 '20 at 08:55
3

You can try this:

<first-component (click)="mySecondComponent.myFunction()"></first-component>
<second-component #mySecondComponent></second-component>

myFunction must be public.

Ploppy
  • 14,810
  • 6
  • 41
  • 58
2

To acheive a cleaner solution follow this process.

Note: In one component call the following method that invokes the event emitter from service and emits it to the other component.

    service.ts:   

    import {Subject} from 'rxjs/Subject';

    private emitter: Subject<any> = new Subject<any>();

      set() {
       this.emitter.next({command: 'set', params:{a:1, b:2});
      };   
      getChangeEmitter() {
        return this.emitter;
      }

    component.ts

    import {Subscription} from 'rxjs/Subscription';

      private listener: Subscription;

     ngOnInit(): void {
        // Listen for changes in the service
  this.listener = this._service.getChangeEmitter()
      .subscribe(paramsFromService => {
        switch (paramsFromService.command) {
          case 'set':
           this.setMethod(paramsFromService);
            break;

          default:
            this.defaultMethod(paramsFromService);
            break;
        }
      });
      }
manideep pabba
  • 457
  • 3
  • 5
1

Add common method in service

import {Injectable} from '@angular/core';
@Injectable()
export class MyService {
  constructor() { }
  doSomething(val) { 
    return !val;
  }
}

Use that in components by injecting that service, one component code follows. Write same as this in other component too.

import {Component, OnInit} from '@angular/core';
import {MyService} from './shared/my-service'; // see angular.io/styleguide

@Component({
  selector: '<my-component></my-component>',
  templateUrl: 'app/name.component.html',
  // This is unnecessary when installing MyService within Root NgModule
  providers: [MyService]
})

export class MyComponent implements OnInit {

  value1: boolean = true;

  constructor(private ms: MyService) {}

  ngOnInit() {  }

  click() { 
    this.ms.doSomething(value1);
  }
}

HTML

<input type="button" (click)="click()">
Veera
  • 397
  • 1
  • 4
  • 21
0

I have got the solution by Using extend Class & using super() in the constructor.

First Class

export class TeamsView {
    constructor(private test:TestService){
    }
    ...
 }

Second Class

export class TeamsForm extends TeamsView {
    constructor(private test:TestService, private router: Router){
      super(test)
    }
    ...
}

I don't know its real method for call the class in the constructor for resolving this but I have found this from one of the Angular sites, and its working for me as well.

Jignesh Vagh
  • 122
  • 1
  • 3
  • 18
  • I also tried initializing a new instance from the second component also passing to it everything its constructor needed and it worked – Mohamed Mahmoud Feb 05 '19 at 23:36
-1

1.) First, you need to import the first component into your target component.

import { FirstComponent } from '../first.component';

2.) Then you need to create an object of the first component like this:

FirstComponentObject = new FirstComponent();

3.) Then call a function of the first component from the target(current) component

FirstComponentObject.FirstComponentFunction();

If you need any help, please comment. Thanks for reading.

ajay hariyal
  • 243
  • 2
  • 9