Angular 8,复选框值可以传递到组件上吗?不在父母/子女关系中 [英] Angular 8, can checkbox value pass onto components? not not in a parent/child relation

查看:73
本文介绍了Angular 8,复选框值可以传递到组件上吗?不在父母/子女关系中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,如果我希望上面的代码将"true"或"false"的"checked"值传递给其他组件,则其内容可以基于"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!!!!

推荐答案

是的,您可以将rxjsBehaviourSubject

您必须在复选框中输入一些值,然后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'}
  }) 
}

通过这种方式,您将从一个组件向可观察的数据发送数据,并将该数据侦听到另一个组件.

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

这篇关于Angular 8,复选框值可以传递到组件上吗?不在父母/子女关系中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆