3

i want to pass the id of a select value to another unrelated component

component 1 :

Html

<select (change)="getSelectedStoreId($event.target.value)">
   <option *ngFor="let store of stores.slice().reverse()" value="{{store.id}}">
      {{store.name}} 
   </option>
</select>

Ts

storeId: any;
getSelectedStoreId(store: any) {
 this.storeId = store;
}

Component 2:

loadItemByStore(storeId: number) {
   this.service.getItemByStore(storeId).subscribe((res: 
   HttpResponse<Item[]>) => {
   this.data= res.body || [];
  }); 
 }
symfony
  • 43
  • 1
  • 5
  • 1
    Does this answer your question? [Angular 6 passing data between two unrelated components](https://stackoverflow.com/questions/51423868/angular-6-passing-data-between-two-unrelated-components) – Roy Jan 11 '21 at 16:30

2 Answers2

6

Use a shared service with Subject or BehaviorSubject, like this:

// service.ts

@Injectable({
 providedIn: 'root'
})
export class MyService {
 sharedValue$ = new Subject();
}

// component a

@Component({
 ...
})
export class ComponentA implements OnInit {
constructor(private myService: MyService) {
}

ngOnInit() {
 // get data
 this.myService.sharedValue$.subscribe(data => {
  // data will update here upon changes
  console.log(data) // 100
 })
}


}

// component b

@Component({
 ...
})
export class ComponentB implements OnInit {
constructor(private myService: MyService) {
}

ngOnInit() {
 // set data
 this.myService.sharedValue$.next(100)
}


}
Yair Cohen
  • 2,032
  • 7
  • 13
0

One good solution is to create an external service that contains this information. The service has a function to get and set/update the value. Then, each time you modify the value in one component, you update it using the service. In the other component you can read this value. You can see an example in this question: this question.

If it is not clear, I can create a specific example.

xavier
  • 1,860
  • 4
  • 18
  • 46