Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value from another component angular 4

Tags:

angular

I have two separate components; a header component containing a select search box, stats component that shows the results depending on the value of the select box, I was wondering if it's possible to refresh the results once the select box change, I thought about using the LocalStorage but it seems like a lazy solution.

like image 408
Ayoub Idelhoussain Avatar asked Jul 19 '17 09:07

Ayoub Idelhoussain


People also ask

How do you access variable from one component to another component?

Go to your app. module. ts and make the provider of that component you want to inherit with other classes: Ex: providers: [DatePipe, AccountComponent] Then go to the class you want access of that variable, and import the component into that: Ex: import { AccountComponent } from '../account/account.

How do you transfer input from one component to another?

If you want to pass data from the child component to the parent component use @Output() and EventEmitter. To pass data from the child to the parent, you have to emit it from the child. The parent will be listening for the event will grab the data.

How do you pass data from one component to another in Angular on button click?

This can be done via input binding, which passes data from one component to another, generally from parent to child. This custom input binding is created by using the @Input() decorator.


1 Answers

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!

like image 198
SrAxi Avatar answered Oct 04 '22 05:10

SrAxi