Deactivate Search Functionality for Users who are not Logged in on an Angular 2 Application

The login component and view are functioning as intended, preventing users from accessing AuthGuard protected routes if they're not logged in. However, I'm facing a challenge with the search bar displayed on the home login screen (actually present on every page of the application). Since it's a component rather than a route, I'm wondering how to disable it for users who are not logged in.

Answer №1

Essentially, when setting up authentication, it is important to include a flag that indicates whether a user is logged in or not. In this example, a boolean is used for this purpose. If the boolean is false, input is disabled. If the boolean is true (meaning the user is logged in), then the input is no longer disabled. This flag may need to be passed as a service if your authentication system is a separate component.

import {Component, NgModule, ViewChild} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <h2>login is "password"</h2>
      <input [value]="password" (input)="password = $event.target.value"> <button (click)="Authed()">login</button>
      <h2>search</h2>
      <input [disabled]="!Auth">
    </div>
  `,
})
export class App {
  name:string;
  Auth: boolean;
  password = "";
  constructor() {
    this.name = 'Angular2';
    this.password = '';
  }

  onKey(event:any) { // without type info
    this.password += event.target.password;
    console.log(this.password);
  }

  Authed(){
    if(this.password === "password"){
      this.Auth = true;
    }
    else{
      this.Auth = false;
    }

  }

}

To see a working example of the above concept, check out this Plunker link.

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

How to import a child component in Angular 2 [v2.4.10] without declaring it in the

I am facing a dilemma with two components parent.component.ts @Component({ selector: 'my-element', template: ` <h4>{{title}}</h4> <child-element></child-element> //<-- I need to retrieve data from ...

Retrieve information from an external JSON source

I am receiving data from an API and storing its JSON in a separate file. The unique URL for accessing this file is shown below: http://events.com/rsvp.php?id=1234 The JSON content on the specified page appears like this: { rsvp: true } Each contact ha ...

npm ERROR! Encountered an unexpected symbol < within the JSON data at position 12842

I keep encountering an error every time I attempt to install a package or run npm install. Despite my limited experience with Angular 4, having only started using it a week ago, I am puzzled by this error. Any guidance on how to resolve it would be greatly ...

When using i18next interpolation in React components, the displayed output may show as [object Object]

In my React application, I am utilizing the next-i18next package. I want to include a React component within my interpolation: import React from 'react'; import { useTranslation } from 'next-i18next'; import { serverSideTranslations } f ...

Ways to induce scrolling in an overflow-y container

Is there a way to create an offset scroll within a div that contains a list generated by ngFor? I attempted the following on the div with overflow-y: @ViewChild('list') listRef: ElementRef; Then, upon clicking, I tried implementing this with s ...

Is there a solution to resolving the type error that I am unable to identify?

I am attempting to implement a custom cursor feature in Vue 3, but unfortunately my code is not functioning as expected. Below you can find the code snippet I have been working on: <template> <div id="cursor" :style="cursorPoi ...

What is the best way to send these values to a JavaScript function and show them one by one on an HTML webpage?

There are 100 values stored in the database. https://i.stack.imgur.com/584Op.jpg I need to retrieve these values from the database using PHP and pass them to JavaScript using Ajax. PHP CODE: for($i=0;$i<=9;$i++) { $random = (10 * $i) + rand(1,10); ...

Seeking a jQuery tooltip plugin that offers support for inline popups similar to overLib

Let's dive into the code: <form name='form 1' action='$action'> input tags <table> some tr tags along with td tags and after some lines in the same table under a td tag <td> <a href="javascript:void(0);" oncli ...

In order to work with the optionSelectionChanges property of the MdSelect directive in Angular Material2, it

Within my application, there is a Material2 select dropdown widget containing several options. app.component.html <md-select placeholder="Choose an option" [(ngModel)]="myOption" (optionSelectionChanges)="setOptionValue(myOption)"> &l ...

Issue with FullPage.js scrollOverflow feature not properly accommodating loaded content

I am currently working on a full-page website and have opted to utilize the Fullpage.js plugin. However, I seem to be facing some challenges when it comes to loading content through an AJAX request. The pages are being populated with JSON content, but for ...

The Vue event was triggered, however there was no response

My current project consists of a Typescript + Vue application with one parent object and one component, which is the pager: //pager.ts @Component({ name: "pager", template: require("text!./pager.html") }) export default class Pager extends Vue { ...

The session feature in Express is malfunctioning

Incorporating express-session into my app, I attempted the following proof of concept (POC):. server.js app.use(session({ secret: 'pal!lap789', // create new redis store. store: new redisStore({ host: 'localhost ...

Why isn't the AngularJS injected view resizing to fit the container?

As a novice delving into a project in the MEAN stack, I'm encountering inconsistent HTML previews. When I view it independently versus running it from the project, the display varies. Here's the intended appearance (in standalone preview): imgu ...

Validation of forms in AngularJS/HTML5 that are nested within one another

Just starting out with AngularJS and experiencing issues with HTML5 nested form validation. I currently have 2 forms; mainFrm (parent form) and stateFrm (a child form). I am struggling to validate each form within its own scope. <form id="mainFrm" ng- ...

Modules are being installed to the application's root directory using NPM

I made a mistake and have tried everything to correct it, but no success. Every time I run 'npm install' on a new node project, it installs all dependencies in the root of the application instead of the expected /node_modules/ directory. For ex ...

The ReactJS application is experiencing issues when run on an outdated version of Chrome, specifically version

I recently set up a new ReactJS project using create-react-app, with node Version 12.22.12. To ensure compatibility with older browsers, I incorporated the polyfill core-js. As a result, the project now functions smoothly on Chrome versions 31 and above; h ...

What is the best way to add a new project and make updates to an existing project within an array?

Looking to add a new project and update existing projects within an array. Here's my plan in pseudo-JSON format. How can I update Project A in MongoDB? { _id : ..., userName: milad , projets : [ { .. projectId, pName, location .... A }, ...

Express middleware generator function causing a type error

I recently implemented a function that takes a middleware function, wraps it in a try-catch block, and then returns the modified middleware function. tryCatch.ts import { Request, Response, NextFunction } from "express"; export default function ...

Eliminate Dates from the Past - Jquery Datepicker

Currently, I am developing a booking system for my client. I have successfully disabled Sundays and Mondays (the days she is not open). However, I am now working on enhancing the functionality by blocking out past dates. Although I have written a function ...

Trouble with a basic array duplication function

function duplicateArray(arr) { var len = arr.length; var dup = new Array(); var j; for (j = 0; j < len; j++) { dup[j] = arr[j]; } console.log(dup); } return; duplicateArray([2, 3, 5]); I appreciate your assistance, There are no errors ...