0
<input type=checkbox [(ngModel)]="myCheckBox" (ngChanged)="!myCheckBox">

for example, if I want the code above to pass the "checked" value, which is "true or false" to other components, so its contents can react based on "myCheckBox" true | false, and they are not in a parent child relationship, is there any way I can do that? Please help, really apprecipate it!!!!

Jerry Wang
  • 15
  • 4
  • if the two components are at time in the app, check too https://stackoverflow.com/questions/59699155/execute-function-between-components/59699411#59699411 – Eliseo Jan 15 '20 at 07:46

2 Answers2

0

You can implement it by different methods. For example: with EventEmitter or rxjs( Subject, BehaviourSubject);

In my example, I did through BehaviourSubject. stackblitz-link

qwerty
  • 679
  • 5
  • 12
0

Yes you can achieve this using rxjs with BehaviourSubject

You have to put some value in checkbox and then onchange you have to call a function which notifies the subscriber in your another component. I am writing up a very basic example for you.

In your sender.component.html you can do like this

<input type=checkbox [(ngModel)]="myCheckBox" (ngChanged)="!myCheckBox" (change)="notifyOtherComponent()">

Then in your service.ts you can do like this

import { BehaviorSubject } from 'rxjs';

private messageSource = new BehaviorSubject('default message');
public currentMessageSubscriber = this.messageSource.asObservable();


notify(message: any) {
   this.messageSource.next(message)
}

And in your sender.component.ts you can do like this

  constructor(private __dataService : DataService){}

  notifyOtherComponent(){
   this.__dataService.notify({msg : 'do something'}) 
  }

And in your listener.component.ts you can subscribe to BehaviourSubject type Observable to listen the latest value like this

constructor(private __dataService : DataService){}

ngOnInit() {
   this.__dataService.currentMessageSubscriber.subscribe((data : any)=>{
    console.log(data) // output : {msg : 'do something'}
  }) 
}

In this way you will be sending data to observable from one component and listening that data into another component.

Fahad Hassan
  • 781
  • 10
  • 20