【问题标题】:Angular 2 - pass boolean "true" from one component to another (not siblings)Angular 2 - 将布尔值“true”从一个组件传递到另一个组件(不是兄弟姐妹)
【发布时间】:2018-10-11 23:12:27
【问题描述】:

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

<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 并隐藏第二个(弹出)组件上的按钮。我该怎么做?有订阅、Observable、EventEmitter?

【问题讨论】:

标签: angular boolean components


【解决方案1】:

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

Public buttonClick = new Subject()

然后在您要发送数据的组件中,联系服务并在其上调用 next()

This.myservice.buttonClick.next (true)

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

This.myservice.buttonClick.subscribe(数据 => 数据)

并且每当您下次调用时,任何订阅都会从任何组件接收您的新数据。

另外,behaviorsubject 是一个会发出初始值的主题

希望这会有所帮助!

【讨论】:

    【解决方案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;
    
                });
    }
    
    }
    

    事件发射器的优点是一旦事件发生就会通知所有订阅的组件。

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 2020-02-05
      • 1970-01-01
      相关资源
      最近更新 更多