1

I have two components with shared services. So click on button in one component, change the boolean value from another component

shared.service.ts

 sharedService.toggle = false;

comp1.component.HTML

<button class="btn btn-primary" (click)="toggleme()">

comp1.component.ts

toggleme(){
this.sharedService.toggle = !this.sharedService.toggle
}

comp2.component.html

<div class="showHide" *ngIf="this.sharedService.toggle">
............
</div>
4
  • use get set to update toggle state in service. Commented Nov 26, 2018 at 13:07
  • but I am sending value from component, set and get in service will do that? Commented Nov 26, 2018 at 13:09
  • The reason why this is not working is beause no one is "telling" the component that the .toggle value has changed. See the answer below how to solve Commented Nov 26, 2018 at 13:21
  • @JacopoSciampi thanks but I took toggleVal = true but onload, <div class="showhide"> is hidden, I want to show this div on load and onclick it should be hidden Commented Nov 26, 2018 at 13:47

1 Answer 1

3

You can use subject/behaviorsubject for this.

shared.service.ts

private toggleState = new Subject();
public toggleState$ = this.toggleState.asObservable();
private toggleVal = false;

emitData(){
   this.toggleVal = !this.toggleVal;
   this.toggleState.next(this.toggleVal);
}

comp1.component.ts

toggleme(){
   this.sharedService.emitData();
}

comp2.component.html

<div class="showHide" *ngIf="this.sharedService.toggleState$ | async">
............
</div>
Sign up to request clarification or add additional context in comments.

9 Comments

I took toggleVal = true but onload, <div class="showhide"> is hidden, I want to show this div on load and onclick it should be hidden
by default u set as false. in ngOnInit() you can call this.sharedService.emitData(); which will set to true and DIV block will be shown.
so by default I took it as true, and then I called this.sharedService.emitData(); in ngOnInit() of comp2.component.ts but still onload that div is hidden
By default, can You show Hello Angular and on click hide it?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.