1

I have two buttons on the main view: Login and Logout. Initially only Login button is shown:

...

<button type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button>
<button type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button>

<router-outlet></router-outlet>

Login button will display a sub-view, once user is authenticated there, I want to pass the result back to main view, if user is authenticated, I want to hide the 'Login' button and show the 'Logout' button.

How can I pass the data from a sub-view back to main view via 'router-outlet'?

Joseph Wu
  • 4,786
  • 1
  • 21
  • 19
  • 2
    Use a common service. Read this, I'm sure you'll find something fitting your case (https://angular.io/docs/ts/latest/cookbook/component-communication.html) – kodeaben Jun 06 '17 at 12:04

2 Answers2

1

To show and hide the button you will use the *ngif structural directive like:

<button *ngIf="!loggedIn" type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button>
<button *ngIf="loggedIn" type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button>

The loggedIn should be a boolean in your component associated with the main-view. I suppose that with the term main-view and sub-view you mean that you have a parent-component and a child-component (for the authentication) form respectively. If this is the case refer to Component Interaction and select the communication that fits you best.

1

You will want to use a service to share information between components. Once the user is authenticated you would want to set a property in this service that indicates the user is authenticated.

Once you have done that you can reference this service to determine if you should show hide something using *ngIf.

Here is a question answered that is similar to yours.

jLee
  • 473
  • 2
  • 5
  • yes, I've created a shared data service to be referenced by the two components (main-view and sub-view), and it works nicely. thank you for the help! – Joseph Wu Jun 08 '17 at 22:48