Switching between various components based on conditions within the same route in Angular

My goal is to have 2 separate views, one for the homepage and another for authentication. I want to display the LoginComponent on the route '/' and the SignupComponent on the route '/signup' if the user is not logged in, otherwise render the components of the homepage. I attempted to use 2 different router outlets for the homepage and authentication (but encountered an issue where the route '/signup' was not configured). Here is my implementation:

  • app.component.html

<div *ngIf="logged$ | async; else login">
  <app-header></app-header>
  <router-outlet></router-outlet>
  <!-- ? Primary Outlet -->
</div>
<ng-template #login>
  <router-outlet name="auth"></router-outlet>
  <!-- ? Secondary Outlet for Auth  -->
</ng-template>

  • app.component.ts

@Component({ ... })
export class AppComponent {
  logged$: Observable<boolean>;

  constructor(private store: Store<State>) {
    this.logged$ = store.select('logged');
  }
}

  • app-routing.module.ts

const routes: Routes = [
  { path: '', children: [/* Homepage Components */] },
  {
    path: '',
    children: [
      { path: '', component: LoginComponent },
      { path: 'signup', component: SignupComponent },
    ],
    outlet: 'auth',
  },
];

@NgModule({ ... })
export class AppRoutingModule {}

Answer №1

One way to avoid displaying two pages on the same URL is by implementing a guard. The guard will be triggered before navigating to the URL and in this scenario, it will redirect you to the login page if you do not have a token (assuming that there is an AuthService with a hasAuthToken method).

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {

  constructor(
    private router: Router,
    private auth: AuthService
  ) { }

  canActivate(): boolean {
    if (this.auth.hasAuthToken()) {
      return true;
    }
    this.router.navigate(['/login']);
    return false;
  }

Routing:

const routes: Routes = [
  { 
    path: '',
    children: [/* Homepage Components */],
    canActivate: [AuthGuard] // Guard added here
  },
  {
    path: '',
    children: [
      { path: '', component: LoginComponent },
      { path: 'signup', component: SignupComponent },
    ],
    outlet: 'auth',
  },
];

@NgModule({ ... })
export class AppRoutingModule {}

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 for obtaining or creating scripts in the package.json file for Angular?

After browsing through the angular.io website, I'm unable to locate the package.json files in the additional documentation section. How exactly is this file created? Do I have to download it from elsewhere? ...

Is there a way to associate a click event with an angular2 template interpolation?

Can a click event be bound to an interpolation? Whenever I try to run the code below, I encounter the following ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at col ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

Stop users from logging in simultaneously on multiple systems

It is possible for the same user and password to be used on multiple computers simultaneously! If person 1 is logged in with a certain username and person 2 logs in from another computer or browser using the same credentials, person 1 will not be automatic ...

Programmatically selecting a row in Angular Datatables

I have an Angular 8 application with the Angular Datatables plugin installed. My goal is to programmatically select a row based on the id parameter from the URL http://localhost:5000/users;id=1. this.route.paramMap.subscribe((params: ParamMap) => { ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

Error in redirection while deploying Auth.js (v5) within a Docker container in a Next.js application

Has anyone successfully integrated the latest version of Auth.js into a production environment with Docker? I am currently utilizing the t3-stack (tRPC, Auth.JS, Prisma, Next.JS). I attempted to upgrade to the beta version with the Prisma Adapter, but enc ...

Unable to access structuredClone on the global object within a Node.js application

structuredClone is causing issues in my NodeJS application. Whenever I try to utilize it, I encounter the error: structuredClone is not defined nodejs. To troubleshoot, I created a simple file and executed the following: console.log({ globals: Object. ...

The TypeScript import statement is causing a conflict with the local declaration of 'Snackbar'

I'm having trouble using the Snackbar component from Material UI in my React app that is written in TypeScript. Whenever I try to import the component, I encounter an error message saying: Import declaration conflicts with local declaration of &apos ...

Configuring a server-side rendered Angular application on Plesk hosting platform

After successfully setting up server side rendering in my Angular app using nguniversal on my local machine, I am now facing the challenge of implementing this on a remote server with Plesk. In my local environment, I can serve the files by running: npm r ...

Troubleshooting: Why is my Datatables data not showing up with Angular 2/4 server side processing

Angular version 4.2.4 Angular-Datatables version 4.2.0 HTML Code Snippet <table datatable [dtOptions]="dtOptions"></table> Component Function ngOnInit() { this.dtOptions = { ajax: { url: "http://localhost:8880/nmets ...

Binding in Angular for internationalization (i18n)

What is the best way to translate a binding using Angular's built-in i18n feature? //translating attribute works fine <mycomponent i18n-myattribute myattribute="just an attribute"></mycomponent> //how to handle translating bi ...

Leveraging foreign key attributes within Angular templates

My technology stack includes Django for the backend with Django Rest Framework and Angular for the frontend. Within the backend, I have defined 2 models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null= ...

Creating a Circle with Pixi.js v4 and Typerscript in IONIC 2

I have been attempting to create a custom class in TypeScript that utilizes PIXI.js to draw circles. Below is the code for my home.ts class: import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'i ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

core.mjs:6484 ALERT There was an issue with reading the 'name' property as it was undefined

I'm encountering an error message in the console.log that I can't seem to resolve... Here is the error message: core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name') https://i.stack.imgur.com/tlun6.png H ...

Signing in to a Discord.js account from a React application with Typescript

import React from 'react'; import User from './components/User'; import Discord, { Message } from 'discord.js' import background from './images/background.png'; import './App.css'; const App = () => { ...

Guide on toggling mat-checkbox according to API feedback in Angular 6

Just starting out with angular 6 and I'm attempting to toggle the mat-checkbox based on the API response. However, I seem to be having trouble. All the checkboxes are showing as checked even when the API response is false. <div class="col-sm-12" ...

The Angular material datepicker fails to organize items in a horizontal row

My web application features an Angular Material datepicker, however, I am facing an issue where not all elements are showing up in a row. The view is as follows: Datepicker To prevent any custom CSS from impacting the view, I have removed all customized ...

What are the steps to integrate an in-memory cache in an Angular frontend using GraphQL queries?

In our Angular frontend application, we are utilizing GraphQL queries with Apollo Client to fetch data. We are interested in implementing caching for our data retrieval process. Initially, we will query the data and store it in the cache. Subsequent requ ...