[英]Angular 2 - pass boolean “true” from one component to another (not siblings)
在一個組件上,我具有觸發功能的按鈕:
<button (click)="open Popup(); hideButton()"></button>
我有一個可以說的buttonService
:我應該用於這兩個組件之間的連接的buttonService
。
在第二個組件(與第一個組件無關的父子組件)中,我有多個像這樣的按鈕:
<button class="element1"></button>
<button [class.hiddenClass]="hideButt" class="element2"></button>
<button class="element3"></button>
第二個組件是彈出窗口,該彈出窗口是在從第一個組件單擊同一按鈕時打開的,這時它還應該觸發hideButton()
函數,將布爾值“ true”傳遞給hideButt
並在該第二個(彈出窗口)組件上隱藏按鈕。 我該怎么做? 使用訂閱,可觀察的EventEmitter嗎?
我認為您可以使用eventEmitter達到這一點,只要您單擊按鈕即可訂閱事件發射器 ,它將立即通知您的第二個組件。
組件之間的選項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;
});
}
}
事件發射器的優點是,一旦事件發生,它將通知所有已訂閱的組件。
您可能會發現rxjs主題有用。 非常適合與服務進行跨組件通信。 在您的服務類別中添加一個屬性,
公共buttonClick =新的Subject()
然后在您要從中發送數據的組件中,聯系服務並在其上調用next()
This.myservice.buttonClick.next (true)
然后,您可以從任何其他組件訂閱主題
this.myservice.buttonClick.subscribe(數據=>數據)
而且,每當您下次致電時,任何訂閱都將從任何組件接收您的新數據。
另外,一個行為主體是一個會發出初始值的主體
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.