I have 2 components (say component A and component B), which are far off in the component hierarchy. I wish to toggle the visibility of the component A based on an event in the component B. I am trying to pass this state through a service that both the components share.
I tried a few approaches and none of them worked for me. I am not sure whether that is expected or if I am doing something wrong.
ControlService
@Injectable()
export class ControlService {
public isOpenState: Boolean = false;
constructor() { }
enable() {
this.isOpenState = true;
}
disable() {
this.isOpenState = false;
}
isOpen() {
return this.isOpenState;
}
}
Approach 1
Component Foo
export class FooComponent implements OnInit {
private isOpen:Boolean;
constructor(controlService: ControlService) {
this.isOpen = controlService.isOpenState;
}
}
HTML
<div id="wrapper" *ngIf="isOpen"> </div>
Approach 2
Component Foo
export class FooComponent implements OnInit {
private isOpen:Boolean;
private controlService: ControlService;
constructor(_controlService: ControlService) {
this.controlService = _controlService;
}
fetchState(){
}
ngOnInit() {
console.log('Hello Component');
}
}
HTML
<div id="wrapper" *ngIf="controlService.isOpen()"> </div>
Approach 3
HTML
<div id="wrapper" *ngIf="controlService.isOpenState"> </div>
None of the above are working for me as expected, the state of the component does not reflect the state in the service. Which of these is the right approach, and what am I missing in them? If neither, what is the correct way to go about this?
*ngIf.