代码之家  ›  专栏  ›  技术社区  ›  John Theoden

角度2-将布尔值“true”从一个组件传递到另一个组件(非同级)

  •  1
  • John Theoden  · 技术社区  · 8 年前

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

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

    2 回复  |  直到 8 年前
        1
  •  4
  •   Midnight_Penguin    8 年前

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

    公共按钮单击=新建主题()

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

    This.myservice.buttonClick.next (true)
    

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

    这我的服务。按钮单击。订阅(数据=>数据)

    无论何时调用next,任何订阅都将从任何组件接收新数据。

    此外,行为主体是将发出初始值的主体

    希望这有帮助!

        2
  •  3
  •   Okyam    7 年前

    我认为您可以使用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>  
    

    在组件中添加此行。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;
    
                });
    }
    
    }
    

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

    推荐文章