get value from another component angular 4

The best way is to send the data to the component.

Use the @Input property to send the data to the controller. Then implement ngOnChanges and execute the function to load the data.

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
    selector: 'second-component',    
})

@Injectable()
export class SecondComponent implements OnChanges {

    @Input()
    selectValue: string;

    ngOnChanges(changes: SimpleChanges) {
           if (changes['selectValue']) {
             //call your function to load the data
           }
    }
    
}

uses

<second-component [selectValue]="bindYourValue"></second-component>

Use Shared Services:

Service:

@Injectable()
export class MyService {
    myMethod$: Observable<any>;
    private myMethodSubject = new Subject<any>();

    constructor() {
        this.myMethod$ = this.myMethodSubject.asObservable();
    }

    myMethod(data) {
        console.log(data); // I have data! Let's return it so subscribers can use it!
        // we can do stuff with data if we want
        this.myMethodSubject.next(data);
    }
}

Component1 (sender):

export class SomeComponent {
    public data: Array<any> = MyData;

    public constructor(private myService: MyService) {
        this.myService.myMethod(this.data);
    }
}

Component2 (receiver):

export class SomeComponent2 {
    public data = {};

    public constructor(private myService: MyService) {
        this.myService.myMethod$.subscribe((data) => {
                this.data = data; // And he have data here too!
            }
        );
    }
}

Check documentation!

Tags:

Angular