After pressing the login button, my intention is to transition to a different page

I am relatively new to web development and working with angular. I have a login component that, upon hitting the LOGIN button, should redirect to another component on a different page. However, currently, when I click the button, it loads the data of the other component on the same page while still displaying the previous login component. I actually want the new component to be displayed on a separate page.

Below is the code structure:

<body>
    <app-loginpage>
        <div id="loader"><img src="assets/img/loaderpreview.svg"></div>
    </app-loginpage>

</body>

In the loginpage.component.html file:

<div class="text-center">
          <button (click)="redirect()" class="btn btn-primary btn-lg loginbtn">
           Login
          </button>
<router-outlet *ngIf="loadcomponent"></router-outlet>

In the loginpage.component.ts file:

export class LoginpageComponent implements OnInit {
  private loadcomponent = false;
  name: string;
  password: any;
  constructor(private router: Router) { }
  ngOnInit() {
  }
redirect() {
      this.loadcomponent = true;
  }

The app.routing.ts file contains the routing setup for the application.

I expect the AdminLayoutComponent to be loaded on a separate page after clicking the login button, but currently, it's loading on the same page. The provided screenshots illustrate the current behavior:

Screenshot showing the Login Component

Screenshot after clicking the login button, indicating the undesired behavior where both components are displayed on the same page

Apologies in advance if I've overlooked something obvious or made a silly mistake.

Answer №1

One way to handle rendering the <app-loginpage> only when a user is not logged in is by placing the <router-outlet> on the main app template, typically found in the app.component.html. Here's an example:

index.html

<body>
  <app-root></app-root>
</body>

app.component.html

<app-loginpage *ngIf="!authenticated"></app-loginpage>
<router-outlet *ngIf="authenticated"></router-outlet>

Answer №2

I recommend separating the login and admin layouts, both accessed through the router.

index.html

<body>
    <my-app></my-app>
</body>

my-app.component.html

<router-outlet></router-outlet>

app.routing.ts

// ......
const routes: Routes  = [
    {
        path: 'login',
        component: LoginPageComponent
    },
    {
        path: 'admin',
        canActivate: [AuthGuard],
        component: AdminLayoutComponent
    },
]
// ......

Next, address these questions:

  1. How can you determine if a user is already logged in?
  2. How can you prevent access to the Admin layout when a user is logged out? Use Angular router guards (see https://angular.io/guide/router#milestone-5-route-guards).

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

Creating an array of objects using Constructors in Typescript

Utilizing TypeScript for coding in Angular2, I am dealing with this object: export class Vehicle{ name: String; door: { position: String; id: Number; }; } To initialize the object, I have followed these steps: constructor() { ...

React-query v5 - Updating or fetching outdated query

I am currently using the Tanstack/react-query v5.12.2 library and I am facing an issue with invalidating or refetching an inactive query using the useQueryClient() function. It seems that something has changed in version 5 of the library. I have tried sett ...

Issue with variable passing during image upload

I am attempting to include an upload button alongside each recipe on my website. In order to save the image path next to each recipe in my database, I need to pass the recipe ID value during the image upload process. However, I keep encountering the same e ...

Height of Owl Carousel on mobile devices

On my desktop, I have an image that covers the entire screen using Owl Carousel. However, when viewed on a phone device, the same image only takes up one-third of the screen size. How can I adjust the height so that it appears taller on a phone? I' ...

Is it possible to stop Angular requests from being made within dynamic innerhtml?

I have a particular element in my code that looks like this: <div [innerHtml]="htmlContent | sanitiseHtml"></div> The sanitiseHtml pipe is used to sanitize the HTML content. Unfortunately, when the htmlContent includes relative images, these ...

JavaScript array with more than 4 elements

I am working on a program where I have created an array and now want to display all the words that contain more than 4 letters. Check out my code snippet below: function oppC(){ var ord = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "co ...

typescript set parameter conditionally within a function

For my upcoming app, I am working on an API that will utilize Firebase FCM Admin to send messages. Below is the code snippet: import type { NextApiRequest, NextApiResponse } from "next"; import { getMessaging } from "firebase-admin/messaging ...

Retrieve the output of the subscribe function in Angular 8 service

I have a service with a method that retrieves the profile image of a user. users.service.ts getPictureProfile() { const headers = new HttpHeaders({ . . .}); const options = { headers }; const body = {...}; return this.http.post(environmen ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...

Error alert: Blinking display, do not dismiss

I am trying to make it so that when the "enviar" button is clicked, the "resultado" goes from being hidden ("display:none") to being visible ("display:block"). This is my html document: <script type="text/javascript"> function showResu ...

Creating two dropdown menus from a PHP array

Currently, I have a PHP array structured like this. $food = array ("Fruits" => array("apple","mango","orange"), "vegies"=> array ("capsicum", "betroot", "raddish"), "bisucuits"=>array("marygold", "britania", "goodday")); My task is to create two ...

The iPage server has encountered a 403 Forbidden Error, preventing

My website is linked with WordPress, but I'm encountering a 403 forbidden error in the sub-menu. Can someone assist me with this issue? I have uploaded a screenshot of the folder in iPage here Additionally, I want my WordPress page to show up correc ...

Using Jest: A guide to utilizing a mocked class instance

When working on my frontend React application, I decided to use the auth0-js library for authentication purposes. This library provides the WebAuth class which I utilize in my code by creating an instance like so: import { WebAuth } from 'auth0-js&ap ...

The CSS rule that is determined to have the nearest bounding class will emerge victorious

Imagine this interesting situation in HTML: <div class="red"> <div class="blue"> ... <-- maybe more nested parents <div class="x">Test</div> </div> </div> If we consider the following ...

Tips for refreshing the appearance of a window in angular when it is resized

I have a chat feature integrated into my application. I am looking to dynamically resize an image within the chat window when the width of the window falls below a certain threshold. Is there a method available to modify the CSS style or class based on the ...

New post: The vue component that was released lacks CSS (NPM)

For the first time, I am releasing a Vue component on NPM and everything seems to be in order, except for one issue - the CSS is missing. While it functions perfectly when tested locally, after installing the npm package in a test project and importing the ...

Styling just a single div when the state changes

I have a scenario where I am rendering 4 divs based on data fetched from my backend. Each div is colored according to a state change. While I have successfully implemented this, the issue is that all 4 divs can be colored in this way simultaneously. I want ...

What is the best way to maximize the use of the space available until reaching a div with varying dimensions each time

I have a div on the left that displays a name, and it can vary in length. On the right, there is another div with buttons. The number of buttons may change, so I am unsure how many will be displayed. Is there a way to utilize only CSS to make sure the fi ...

"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions. Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description wi ...

Using a JavaScript class rather than an ID for toggling visibility

As a complete newbie to JavaScript, I've come across similar questions but I'm lost when it comes to coding - help needed! So here's the code I have so far, and I'm hoping someone can assist me. Currently, I have JavaScript set up to s ...