moh
moh

Reputation: 443

angular 5 change header buttons in diffrent condition

Hi im working on api and angular 5 for client side I need to change navbar buttons . when user is logged in (signin and register may change to logout button) ... i saved a key like logged in local storage and i check this value is set or not ... if it is set i change button like below. this code user will redirect to home page but header component (the buttons condition ) will not changed ... after refresh browser change will takes effect: how can i solve this issue?

navbar component.ts:

import {Component, OnInit} from '@angular/core';
import {AuthUserService} from "../../services/auth-user.service";
import {Router} from "@angular/router";

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
  public is_logged : boolean;

  constructor(private http: AuthUserService,private  router : Router) {

  }

  ngOnInit() {

    let locals = localStorage.getItem('logged');

    if (locals == '1') {
      this.is_logged = true;
    }
  }

  logout() {
    this.is_logged = false;
    this.http.logout();
    this.router.navigate(['/']);

  }


}

navbar.html

<div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom box-shadow">
  <h5 class="my-0 mr-md-auto font-weight-normal">Company name</h5>
  <nav class="my-2 my-md-0 mr-md-3">
    <a class="p-2 text-dark" href="#">comming soon</a>
    <a class="p-2 text-dark" href="#">comming soon</a>
    <a class="p-2 text-dark" href="#">comming soon</a>
    <a class="p-2 text-dark" href="#">about</a>
  </nav>
  <div *ngIf="is_logged;else otherc">
    <a class="btn btn-outline-primary" href="#" (click)="logout()">log out</a>

  </div>
  <ng-template #otherc>
    <a class="btn btn-outline-primary" href="#">sign up</a>
    <a class="btn btn-outline-success" href="#" routerLink="/login">log in</a>
  </ng-template>
</div>

and its my login.component.ts

import {Component, OnInit} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Router} from "@angular/router";
import {User} from "../../models/user";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  user: User = new User();


  constructor(private http: HttpClient,
              private router: Router) {
  }

  ngOnInit() {
    // this.http.logout();
  }

  onSubmit({value, valid}) {
    if (!valid) {
      console.log("form in invalid!");
      return false;
    }
    let username = value.username;
    let password = value.password;

    this.http.post<any>("http://localhost:8000/login/", {username: username, password: password})
      .subscribe(
        user => {
          if (user && user.token) {
            console.log(user);
            localStorage.setItem('ut', JSON.stringify(user.token))
            this.router.navigate(['/']);
          }
        }
      );
  }
}

and here is my app.component html file

<app-navbar>
</app-navbar>
<app-home></app-home>
<div class="container">
  <router-outlet></router-outlet>
</div>

<app-footer></app-footer>

Upvotes: 1

Views: 2305

Answers (1)

AlexITC
AlexITC

Reputation: 1074

I haven't checked all your code, the way that I have handled that is creating a service that can tell me when the user is logged in or not, in case that it is logged in, it can tell me the current user.

Then, instead of having complex if else logic, you can create different containers, one for the logged in case, another for the not logged in, using the hidden attribute and the Angular data binding.

An example (taken from https://github.com/AlexITC/crypto-coin-alerts/blob/master/alerts-ui/src/app/app-navbar/app-navbar.component.html#L19):

<ul [hidden]="isAuthenticated()" class="nav navbar-nav navbar-right">
  <li>
    <a routerLink="/new-account">{{'label.newAccount' | translate}}</a>
  </li>
  <li>
    <a routerLink="/login">{{'label.login' | translate}}</a>
  </li>
</ul>

<ul div [hidden]="!isAuthenticated()" class="nav navbar-nav navbar-right">
  <li>
    <button type="button" class="btn btn-link">{{getAuthenticatedUser()}}</button>
  </li>
  <li>
    <button type="button" class="btn btn-link" (click)="logout()">{{'label.logout' | translate}}</button>
  </li>
</ul>

Here is the auth service: https://github.com/AlexITC/crypto-coin-alerts/blob/master/alerts-ui/src/app/auth.service.ts#L14

Upvotes: 1

Related Questions