angular 4 execute function from another component

Solutions on MaxInterview for angular 4 execute function from another component by the best coders in the world

showing results for - "angular 4 execute function from another component"
Antonio
23 Oct 2017
1//Angular 4 execute function from another component
2
3 didn't get time to test it but similar solution worked for me. the code created for your need.
4
5Create a service like this
6
7import { Injectable } from '@angular/core';
8import { Observable } from 'rxjs/Observable';
9import { Subject } from 'rxjs/Subject';
10
11@Injectable()
12export class MessageService {
13    private _listners = new Subject<any>();
14
15    listen(): Observable<any> {
16       return this._listners.asObservable();
17    }
18
19    filter(filterBy: string) {
20       this._listners.next(filterBy);
21    }
22
23}
24then implement in your header component like this
25
26// header.component.ts
27@Component({
28    selector: 'header',
29    templateUrl: `
30        <section class="container">
31            <button (click)="clickFilter()">Open filter</button>
32        </section>
33    `
34 })
35
36export class HeaderComponent {
37     @Output() onFilter: EventEmitter = new EventEmitter();
38
39     constructor(private _messageService: MessageService){}
40     clickFilter():void {
41         // this.onFilter.emit('Register click');
42         this._messageService.filter('Register click');
43     }
44 }
45then use in your store component like this
46
47@Component({
48    selector: 'store',
49    template: `<article class="card">
50                 Test
51              </article>`
52})
53
54export class StoreComponent {
55    constructor(private _messageService: MessageService){
56        this._messageService.listen().subscribe((m:any) => {
57            console.log(m);
58            this.onFilterClick(m);
59        })
60    }
61
62    onFilterClick(event) {
63        console.log('Fire onFilterClick: ', event);
64    }
65 }
66The concept is that you can use observable in a service and subscribe in the component where you want it (store.component) and can send event from anywhere in the app like i did in the header.component
67
68I hope it will help you
similar questions