I'm having trouble with implementing a basic show/hide feature for the login and logout options in the navigation bar using Angular. Can anyone help me figure out why it's

Is there a way to display the functionality after logging in without using session storage or implementing the logout function? The HTML for navigation is provided below.

<nav class="navbar navbar-expand-sm navbar-light bg-light">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a *ngIf = "!invalidLogin" class="nav-link" routerLink="create">Add New Music</a>
                    {{!invalidLogin}}
                </li>
                <li class="nav-item">
                    <a *ngIf = "!invalidLogin" class="nav-link active" routerLink="list">Manage Items</a>
                </li>
                <li class="nav-item">
                    <a *ngIf = "!invalidLogin" class="nav-link" routerLink="customerlist">Manage Customers</a>
                </li>
            </ul>

            <ul class="navbar-nav navbar-collapse justify-content-end">
                <li class="nav-item">
                    <a class="nav-link" routerLink="addcustomer">SignUp</a>
                </li>
                <li class="nav-item">
                    <a *ngIf = "invalidLogin" class="nav-link" routerLink="login">Login</a>
                </li>
            </ul>
        </nav>

The attempt to set invalidLogin to true in ngOnit() did not work. See the code snippets for Navigation Component and Customer Service below for insights on how this property handles the functionality.

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

  invalidLogin: boolean = true;

  constructor() { }

  ngOnInit(): void {
    // this.invalidLogin = true;
  }

}
@Injectable({
  providedIn: 'root'
})
export class CustomerService {

  username: string = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e7eaf5fae2c3e4eee2eaefade0ecee">[email protected]</a>";
  password: string = "divya123";

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

  doLogin(user: Login){
    let temp = false;
    if((user.username === this.username) && (user.password === this.password)){
      this.nav.invalidLogin = false;
      temp = true;
    }else{
      temp = false;
      // this.message = "Invalid Credientials"
    }
    return temp;
  }
}

In the login component below, you can observe the service class being called to set the property "this.nav.invalidLogin = false", and the subsequent actions performed based on that.


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

  login: Login;
  message: string;

  constructor(private router: Router, private nav : NavigationComponent, private custService: CustomerService) { }

  ngOnInit(): void {
    this.login = new Login(); 
  }

  doLogin(user: Login){
    if(this.custService.doLogin(user)){
      console.log("Invalid user : ",this.nav.invalidLogin);
      this.router.navigate(["list"]);
    }else{
      this.message = "Invalid Credientials"
    }
  }

}

Answer №1

Using observables would be a great solution for instant updating of values.

I've streamlined your code to focus on the essential parts, removing unnecessary classes and imports in the classes.

Here's how I would adjust your HTML:

<nav>
  <!-- Subscribing to the new class level observable value -->
  <ul *ngIf="!(invalidLogin | async)">
    <li>
      <a>Add New Music</a>
      - {{invalidLogin | async}}
    </li>
    <li>
      <a>Manage Items</a>
    </li>
    <li>
      <a>Manage Customers</a>
    </li>
  </ul>

  <ul *ngIf="(invalidLogin | async)">
    <li>
      <a>SignUp</a>
    </li>
    <li>
      <a>Login</a>
    </li>
  </ul>
</nav>

Consider this adjustment for your component:

export class NavigationComponent implements OnInit {
  invalidLogin: Observable<boolean>;

  constructor(private customerService: CustomerService) {}

  ngOnInit(): void {
    this.invalidLogin = this.customerService.doLogin({
      username: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caaea3bcb3ab8aada7aba3a6e4a9a5a7">[email protected]</a>",
      password: "not-matching"
    });
  }
}

And here is your service:

import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";

@Injectable({
  providedIn: "root"
})
export class CustomerService {
  username: string = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="67030e111e0627000a060e0b4904080a">[email protected]</a>";
  password: string = "divya123";

  doLogin(user: any): Observable<boolean> {
    if (user.username === this.username && user.password === this.password) {
      return of(false);
    }
    return of(true);
  }
}

A suggestion for better readability: Consider renaming the component's variable invalidLogin to validLogin. This will eliminate double negatives in the template, making it easier to understand. Remember to adjust the templates accordingly if you make this change. I highly recommend this update for clarity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The 'disabled' property is not found in the 'MatButton' type, however, it is necessary in the 'CanDisable' type

Issue found in node_modules/@angular/material/core/option/optgroup.d.ts: Line 17: Class '_MatOptgroupBase' does not correctly implement interface 'CanDisable'. The property 'disabled' is missing in type '_MatOptgroupBas ...

Unable to proceed due to lint errors; after conducting research, the issue still remains

I'm still getting the hang of tslint and typescript. The error I'm encountering has me stumped. Can someone guide me on resolving it? I've searched extensively but haven't been able to find a solution. Sharing my code snippet below. (n ...

The TS2339 error has occurred because the "email" property cannot be found on the specified "Object" type

I encountered an issue while using Angular 5, here is the code snippet : signIn(provider) { this._auth.login(provider).subscribe( (data) => { console.log(data); this.hideForm = false; this.emaill = data.email; ...

Creating a custom data type using values from a plain object: A step-by-step guide

I recently came across an object that looks like this: const myObject = { 0: 'FIRST', 10: 'SECOND', 20: 'THIRD', } My goal is to define a type using the values from this object, similar to this: type AwesomeType = &apos ...

Testing an Angular component with @Input through unit testing

I am dealing with an angular component that utilizes an @input attribute and processes it in the ngOnInit. When writing unit tests for @inputs, I usually set the value using component.inputproperty=value. However, in this case, I cannot do so due to the ...

Tips for changing a value in an ngIf template

Hi there, I'm fairly new to Angular and I am trying to make some changes in the ngIf template. I have created a component called research-list and I want to display the research data defined in research-list.ts file. However, when I try to use modify( ...

I'm currently learning about things that never change and struggling to grasp their meaning

I'm currently delving into the world of immutable.js record and trying to wrap my head around it. However, this particular piece of code is really throwing me for a loop. Here's my Question: I understand [import, export,const], but what ex ...

Tips for composing content on a sanitized input?

In my small application, I have a feature where a question is displayed with certain words hidden and needs to be filled in by the user. The format of the question looks like this: The {0} {1} {2} his {3} off To achieve this functionality, I wrote the f ...

Embracing Typescript version 2.7 and above allows for utilizing multiple types within a parameter, enabling developers to efficiently handle specific properties

Imagine a scenario where a ChildClass is extending the ParentClass. You can view the code on Stackblitz here. The ChildClass simply adds a public property called "brainPower": class ParentClass{ _me: string; constructor() { this._me = "I'm ...

What is the best way to incorporate a Vue single file component into a Typescript-infused view?

Despite trying numerous methods, I consistently encounter build or runtime errors. To my surprise, I have not come across a functional example or post related to this inquiry after extensive research. I initiated a new project with Typescript using the Vue ...

Rewriting URLs in Angular 2

I am a beginner in Angular 2 and I am currently working on a project that requires URL rewriting similar to that of ' '. In Zomato, when you select a city, the city name appears in the URL like ' ', and when you select a restaurant, t ...

Ways to ensure that DOM elements have completed rendering in Angular 2 Unit Tests

I am currently working on a test that focuses on an HTML element, sets its value, and triggers the blur event handler. The blur event is supposed to initiate a validation check which, if invalid, should disable a save button. During a test run, this proce ...

How can you create an interface where the value type is determined by the key, but not all keys are predefined?

Below is an illustration of a data structure that I aim to define as a type in TypeScript: const dataExample = { Folder: { "Filename.js": { lines: { total: 100, covered: 80, ...

Rendertron always renders base routes as empty

I'm running into an issue while trying to use rendertron via an Apache proxy - all the base routes are showing up as "null." Could this be due to a configuration error on my part? Any help would be greatly appreciated. The Rendertron service is curre ...

How can I display a sessionStorage string in an Angular 8 HTML view?

I'm looking to show the data stored in sessionStorage on my angular view. This is my current session storage: sessionStorage.getItem('username'); In my dashboard.ts file, I have: export class DashboardComponent implements OnInit { curr ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Oops! There was an unexpected error in the authGuard: [object Object] was not caught as expected

I've been working on implementing authGuard in my app, but I keep encountering an error. Below is the guard implementation: canActivate(route: ActivatedRouteSnapshot): Observable<boolean> { /** * Returning an observable of type boolea ...

Restrict the discriminator value in a discriminated union from any other string literal union type in TypeScript

My discriminated union is quite basic, but I want to restrict the discriminator to only allow specific values that come from another string literal union type. This would simplify the process of adding new "cases" to the discriminated union. Here is a str ...

``There is an issue with Cross-Origin Resource Sharing (CORS) in a Node.js application utilizing TypeScript

I've encountered some issues with my application, specifically regarding CORS. I suspect it may be due to a misconfiguration on my server. The problem arises when I attempt to create a user in my PostgreeSQL database via the frontend. I have a tsx com ...

Best practices for utilizing ngrx/store in Angular 2

As I am refactoring my Angular 2 applications to follow the ngrx pattern, some questions have arisen in my mind: My application retrieves a list of apps and a list of app categories. Can I manage state like "selectedCategory" (where only one can be select ...