Angular 2 - 从一个组件传递布尔“true”到另一个组件(不是兄弟姐妹)

时间:2018-05-01 22:07:57

标签: angular boolean components

在一个组件上,我有触发功能的按钮:

<button (click)="open Popup(); hideButton()"></button>

我有,让我说:buttonService我应该用它来连接这两个组件。

在第二个组件(不是与第一个组件相关的父子组件)中,我有多个按钮,如下所示:

<button class="element1"></button>
<button [class.hiddenClass]="hideButt" class="element2"></button>
<button class="element3"></button>

第二个组件是从第一个组件点击相同按钮时打开的弹出窗口,此时它还应该触发hideButton()函数将布尔值“true”传递给hideButt并隐藏第二个组件上的按钮( popup)组件。我该怎么做?使用subscribe,Observable,EventEmitter?

2 个答案:

答案 0 :(得分:2)

我认为你可以使用eventEmitter来达到这个目的,只要你点击了你需要订阅event emitter的按钮,它就会通知你的第二个组件。

组件之间的选项1  您将在要触发更改的组件中执行此操作

导入

import { Injectable, EventEmitter } from '@angular/core';

声明

 @Output()variableEvent: EventEmitter<any> = new EventEmitter();

设置您想要更改的值

   public sendChange(){

 this.variableEvent.emit(value);

}

在要获取值的组件的模板中添加它

 <child (sendChange)="getValue($event)"></child>  

在component.ts中添加此行

private getValue($event){
//Get the value
}     

使用服务的选项2

  export class Service {
    public change: EventEmitter<any> = new EventEmitter();

    public setdata(value) {

        this.change.emit(value);
    }
}

设置数据的组件

export class SetDataComponent {

constructor(private service: Service) {}

private setData(){

this.service.setData(value);

}

}

将收到数据的组件

export class GetDataComponent {

constructor(private service: Service) {}

private getData()
{

this.service.change.subscribe(value => {
               let dataRecieve = value;

            });
}

}

事件发射器的出现是,一旦事件发生,它将通知所有订阅的组件。

答案 1 :(得分:2)

您可能会发现rxjs主题很有用。它非常适合与服务进行跨组件通信。 在服务类中添加属性

公共按钮点击=新主题()

然后在您想要发送数据的组件中,联系服务并调用next()就可以了

This.myservice.buttonClick.next (true)

然后您可以从任何其他组件订阅您的主题

This.myservice.buttonClick.subscribe(data =&gt; data)

每当您拨打下一个电话时,任何订阅都会从任何组件接收您的新数据。

此外,behaviorubject是一个将发出初始值的主题

希望这有帮助!