在angular 2应用程序中,我有3个不同的组件Comp_A,Comp_B和 Comp_C。 Comp_C与其他2没有父子关系或兄弟关系 组件。 Comp_B是Comp_A的子代。我点击了一下按钮 EventEmitter通过sharedService隐藏/显示div的事件 在Comp_C中阻止。在我的Comp_A代码中,我可以隐藏div块 Comp_C。但无法再从Comp_B中再次显示相同的div 帮助相同的事件发射器和共享服务。
答案 0 :(得分:1)
**Comp_C**
import {Component, OnInit} from 'angular2/core';
import {ComponentA} from 'src/ComponentA';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'my-app',
templateUrl: './main-page.component.html',
providers : [SharedService]
})
export class AppComponent implements OnInit {
viewList : Boolean;
constructor(ss: SharedService) {
this.viewList = false;
this.ss = ss;
}
ngOnInit() {
this.subscription = this.ss.getEmittedValue()
.subscribe(item => this.viewList=item);
}
}
**main-page.component.html**
<div>
<div *ngIf = " viewList == false">
<mydata-list-component> </mydata-list-component>
</div>
</dive>
----------
**Comp_A**
import {Component} from 'angular2/core';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'main-app',
templateUrl: './menu-bar.component.html',
})
export class MainComponent {
ss;
constructor(ss: SharedService) {
this.ss = ss;
}
hideListView() {
this.ss.hide();
}
}
**menu-bar.component.html.html**
<div>
<button (click)="hideListView()">hideListView</button>
</dive>
----------
**Comp_B**
import {Component} from 'angular2/core';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'main-app',
templateUrl: './menu-bar-sec-page.component.html',
})
export class MainComponent {
ss;
constructor(ss: SharedService) {
this.ss = ss;
}
show ListView() {
this.ss.show();
}
}
**menu-bar.component.html.html**
<div>
<button (click)="showListView()">hideListView</button>
</dive>
----------
**SharedService**
import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core'
@Injectable()
export class SharedService {
@Output() fire: EventEmitter<any> = new EventEmitter();
constructor() {
console.log('shared service started');
}
show() {
console.log('show started');
this.fire.emit(false);
}
hide() {
console.log('hide started');
this.fire.emit(true);
}
getEmittedValue() {
return this.fire;
}
}