Iqbal_kk
Iqbal_kk

Reputation: 13

Show/Hide div according toggle button change in Angular 9

I have 2 separate component in my Angular application. One of the component is the top navigation bar and it contain the toggle button. Other component is a Dashboard and is in a separate module.

My Dashboard contain 2 div in which either one should be hide/show based on toggle button change in Top Navigation bar component.

example: When toggle toggle button is checked div 1 should be shown and div 2 should be hidden.

Can someone give me a solution with a stack-blitz sample ?

Upvotes: 1

Views: 1491

Answers (3)

Jens Alenius
Jens Alenius

Reputation: 1931

  1. Add a service to the main module that all modules share. You can inject that service in both components. You then need to add a subject to the service that the dashboard can subscribe on. The navigation will use the service to Trigger the subject. Google ‘basic service with subject’
  2. You can add an query parameter to the url. That dashboard can then look for it to know what toggle state it is in. Something like: ?toggle=true. It’s not pretty but it have one advantage. You can bookmark or send the url to someone and it will know the toggle state.

Remember to use a button (not anchorlink) for toggle

Upvotes: 0

Amod Shinde
Amod Shinde

Reputation: 154

Here I assume there is binding across two separate components who are neither a child or parent of each other.

One way this can be handled is:

the Toggle flag can be set and unset with the help of Subject from Rxjs and a service. StackBlitz Link

Upvotes: 1

Chenna
Chenna

Reputation: 2623

Angular docs have great examples to handle component interaction

Stackblitz: Link (Assuming your components are neither siblings nor in same module)

Upvotes: 0

Related Questions