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

What is the process of extracting multiple attributes from an object that has been selected by a user using mat-options (dropdown list) in Angular?

Summary: A dropdown list contains objects, unsure how to capture multiple attributes of selected object. Current Implementation: I have successfully created a dropdown list that displays the details of an object retrieved through an API call: <mat-f ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Unable to finish the execution of the ionic capacitor add android command

My current project needs to add android as a supported platform, so I tried running the command: ionic capacitor add android. However, when I run the command, it stops at a prompt asking me "which npm client would you like to use? (use arrow keys)", with ...

I am facing an issue with the Angular2 Modal Form where it only displays the data but does

Hey there, I recently started diving into Angular and I'm loving the learning process. Currently, I've managed to successfully load a form into my Modal when clicking on "viewDetails". However, as soon as I modify the Form from <form ngNoFo ...

Utilizing a created OpenAPI client within a React application

Using the command openapi-generator-cli generate -i https://linktomybackendswagger/swagger.json -g typescript-axios -o src/components/api --additional-properties=supportsES6=true, I have successfully generated my API client. However, despite having all th ...

` `angular2 get the element reference of a component that is not a direct descendant` `

Within my application, the structure is as follows: <fin-header></fin-header> <main></main> <fin-footer></fin-footer> I would like to implement scrolling within the header to a specific component within main. However, ...

Angular2 Dependency Injection with NPM-MQTT

I'm facing some challenges integrating the MQTT package into my Angular2 TypeScript project (created with angular-cli). When using var mqtt = require('mqtt');, I encounter the error Cannot find name 'require'. Therefore, I attemp ...

NGRX effect in Nativescript Angular loses state when the app is suspended on iOS

While using NGRX with Nativescript Angular to manage state and fetch data from the server, I've encountered an issue when suspending the app on IOS. Whenever the app is in the middle of fetching data from the server and gets suspended, the entire proc ...

What is causing the issue with TypeScript's React.createRef() and its compatibility with the material-ui Button element?

Running on React version 16.13.1, my component class includes a Material-UI Button component and a RefObject to access the button element. class Search extends React.Component<any, any>{ constructor(props: any) { super(props) this.streetV ...

Does the router navigate function instantly update the router URL?

I'm testing whether the navigate function will immediately alter the router URL upon execution. this.router.navigate(['/home/products']); if (this.router.url.includes('/home/products')) console.log('URL has been changed&apos ...

What is the correct way to declare a class as global in TypeScript?

To prevent duplication of the class interface in the global scope, I aim to find a solution that avoids redundancy. The following code snippet is not functioning as intended: lib.ts export {} declare global { var A: TA } type TA = typeof A class A { ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Utilizing Typescript to implement an interface's properties

After declaring an interface as shown below interface Base { required: string; } I proceeded to implement the interface in a class like this class MyClass implements Base{ method(): void { console.log(this.required); } } However, I ...

What is the proper error type to use in the useRouteError() function in react-router-dom?

In my React project, I am utilizing the useRouteError() hook provided by react-router-dom to handle any errors that may arise during routing. However, I'm uncertain about the correct type for the error object returned by this hook. Currently, I have ...

Utilizing the componentDidUpdate method to update the state within the component

I have a scenario where two components are enclosed in a container. One component is retrieving the Id of a publication, while the other is fetching the issue date related to that specific publicationId. When I retrieve an Id, let’s say 100, it successf ...

Having Trouble with React, TypeScript, and MUI Tabs? Dealing with Overload Errors?

Currently, I'm in the process of building a component using MUI Tabs. Here's a snippet of my code: <Box> <Tabs value={value} onChange={handleChange} variant='fullWidth'> {RoomTabs.map((tab, index) => ( ...

What is the best way to manage user sessions for the Logout button in Next.js, ensuring it is rendered correctly within the Navbar components?

I have successfully implemented these AuthButtons on both the server and client sides: Client 'use client'; import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import Link from 'next/link'; ...

The positioning of the Zorro table column remains flexible despite the presence of nzLeft

I am currently developing a project using Angular. Within one of my components, I have a table that displays some data. This table is generated by the ng-zorro table module. However, I've encountered an issue where setting a table column or header wi ...

The missing binding.node file is causing an issue with Node-sass

Previously, my angular project 7.1 was running smoothly until I upgraded to ubuntu 19.10 and encountered an error upon running npm install: > [email protected] install /home/gabb/dev/homepage/node_modules/node-sass > node scripts/install.js Do ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...