user1908375
user1908375

Reputation: 1089

Access variables of other components in Angular

I am developing an app in Angular using TypeScript:

My app.component has a navigation on the top, and then router-outlet of other components

<navigation></navigation>
<router-outlet></router-outlet>

Navigation

@Component({
  selector: 'navigation',
  directives: [ROUTER_DIRECTIVES],
  template: `{{ HERE SHOULD BE USERNAME }}    <a [routerLink]="['Home']">Home</a> | <a [routerLink]="['Logout']">Logout</a>`
})
export class NavigationComponent {}

Login (loaded inside router-outlet)

@Component({
    selector: 'login-component',
    templateUrl: 'app/components/login/login.html',
})
export class LoginComponent {

  username ;

  constructor(public router: Router, public http: Http) {
  }
...
}

The login.component manages the login procedure. After the user is logged in -> I'd like to display its user-name in Navigation.component. How could I pass the User-Name to Navigation.component from login.component ? Or how to access a variable username inside login.component from Navigation.component ?

Upvotes: 2

Views: 1670

Answers (1)

JB Nizet
JB Nizet

Reputation: 692281

Make them both use a common service, and store the username in the service.

The login component stores the username in the service:

userService.setUser(theUser);

The navigation component allows getting the user from the service:

getUser() {
    return userService.getUser();
}

The view of the navigation component uses

{{ getUser() }}

Upvotes: 4

Related Questions