Get value from another angular 4 component
I have two separate components; a header component containing a select search box, a statistics component that shows results based on the value of the select box, I was wondering if it is possible to update the results after changing the select box, I thought of using it LocalStorage
, but it seems like a lazy solution.
source to share
Use shared services:
Services:
@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 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!
}
);
}
}
source to share
I think for your case it is best to use service
for communication between components.
Check out an example in the Angular documentation: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
source to share
The best way is to send data to a component.
Use the @input property to send data to the controller. Then execute ngOnChanges and execute a function to load 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>
source to share