Angular 8, can checkbox value pass onto components? not not in a parent/child relation

若如初见. 提交于 2020-01-16 11:58:21

问题


<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!!!!


回答1:


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

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




回答2:


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.



来源:https://stackoverflow.com/questions/59744286/angular-8-can-checkbox-value-pass-onto-components-not-not-in-a-parent-child-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!