Reputation: 11
I have component HeaderComponent with the following template :
<button *ngIf="isConnected">Logout</button>
And the template in composant LoginComponent
<button (click)="login()">login</button>
In AppComponent :
<app-header></app-header>
<app-login></app-login>
I would like to show Logout button when I click login button
Thank you for your helps
Upvotes: 1
Views: 1316
Reputation: 10944
Welcome Paul.
This is a good use case for a service. Generate a service with ng g service <path>/<serviceName>
. Inside, we can put a subject
that the HeaderComponent
can subscribe
to, and the LoginComponent
can pass values to.
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class LoginStateService {
subject = new Subject<boolean>();
}
You may actually want to bundle all of your login functions in this service, but I'll just describe setting the state for simplicity.
To subscribe in the HeaderComponent
loginSub = new Subscription();
isLoggedIn = false;
constructor(private loginState: LoginStateService) {}
ngOnInit(): void {
this.loginSub = this.loginState.subject.subscribe(
(value) => (this.isLoggedIn = value)
);
}
ngOnDestroy(): void {
this.loginSub.unsubscribe();
}
Unsubscribing is probably not necessary here, but it's good practice to prevent memory leaks.
To pass a value from Login Component
constructor(private loginState: LoginStateService) {}
login() {
//Do some login stuff
this.loginState.subject.next(true);
}
logout() {
//Do some logout stuff
this.loginState.subject.next(false);
}
Upvotes: 1
Reputation: 2361
you have a couple of options, you can work with Input() and Output() or you could work with a shared service.
for example: in login.service.ts
isConnected = false;
in login.component.ts
public login(){
this.loginService.isConnected = true;
}
in app.component.html
<app-header *ngIf="loginService.isConnected></app-header>
Upvotes: 0