Angular 8,复选框值可以传递给组件吗?不在父/子关系中 [英] Angular 8, can checkbox value pass onto components? not not in a parent/child relation
问题描述
<input type=checkbox [(ngModel)]="myCheckBox" (ngChanged)="!myCheckBox">
例如,如果我希望上面的代码将checked"值(true 或 false")传递给其他组件,那么它的内容可以根据myCheckBox"做出反应 true |假的,而且他们没有父子关系,有什么办法可以做到吗?请帮助,真的很感激它!!!!
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!!!!
推荐答案
是的,您可以使用 rxjs
和 BehaviourSubject
Yes you can achieve this using rxjs
with BehaviourSubject
您必须在复选框中放置一些值,然后 onchange
您必须调用一个函数来通知另一个组件中的订阅者.我正在为您编写一个非常基本的示例.
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.
在你的 sender.component.html
你可以这样做
In your sender.component.html
you can do like this
<input type=checkbox [(ngModel)]="myCheckBox" (ngChanged)="!myCheckBox" (change)="notifyOtherComponent()">
然后在你的 service.ts
中你可以这样做
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)
}
在你的 sender.component.ts
中你可以这样做
And in your sender.component.ts
you can do like this
constructor(private __dataService : DataService){}
notifyOtherComponent(){
this.__dataService.notify({msg : 'do something'})
}
并且在您的 listener.component.ts 中,您可以订阅 BehaviourSubject
键入 Observable
以收听这样的最新值
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'}
})
}
通过这种方式,您将从一个组件向 observable 发送数据,并将该数据收听到另一个组件中.
In this way you will be sending data to observable from one component and listening that data into another component.
这篇关于Angular 8,复选框值可以传递给组件吗?不在父/子关系中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!