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

Can the type of a prop be specified in the parent component before it is passed down to the children components that utilize the same prop?

In my codebase, I have a component called NotFoundGuard. This component only renders its children if a certain condition is true. Otherwise, it displays a generic fallback component to prevent redundancy in our code. I am trying to figure out if there is ...

The value of a checkbox in Ionic 2

I have implemented the code for reading checkbox values in Ionic 2 following the answer provided. However, I encountered an error message in the console: Cannot read property 'indexOf' of undefined Here is my home.html code: <form #leadsF ...

When defining properties/data in Vue mixins, the properties/data of the mixin are not accessible

A vue mixin is being used to store information (referred as `world` in the example below) that needs to be accessed in multiple vue components without having to import it every time. Check out the code snippet: <template> <ol> <li> ...

An issue occurred with Ionic 4: TypeError - Unable to access property 'name' as it is undefined

None of the answers to similar questions have provided a solution for me SITUATION: I've been setting up a SQL Server connection from my Ionic app. You can check out my previous question for more details The workflow goes as follows: Ionic connects ...

Tips for sorting multiple rows based on the primary column in MUI DataGrid ReactJS

https://i.stack.imgur.com/T9ODr.png Is there a way to utilize Material UI DataGrid to build a table that matches the structure displayed in the linked image? I have successfully created a basic table with DataGrid, but I'm struggling to add multiple ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

NativeScript: TypeScript for Formatting Numbers

Being a beginner in NativeScript, I'm finding it difficult to find basic information through Google search. But now, I have a specific question: I have the number 1234567.89 stored in a variable, and I want to display it in a label with the format ...

Angular Forms, mark a form as invalid if a p-select element retains its original value

I am looking to prevent the submit button from being enabled until a user makes changes in any of the form controls. The challenge I'm facing is that while required input fields are easy to handle, there is also a select control with three options. De ...

Passing parameters to an Angular CLI ejected app

Currently, I am utilizing @angular/[email protected]. I have leveraged the new eject feature to modify the webpack configuration. Now, I find myself perplexed on how to pass parameters to my build process. For instance, how can I execute ng build --p ...

Creating variables in Typescript

I'm puzzled by the variable declaration within an Angular component and I'd like to understand why we declare it in the following way: export class AppComponent { serverElements = []; newServerName = ''; newServerContent = &apos ...

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

Tips for achieving server-side pagination with client-side sorting

Currently utilizing Angular Material's data grid, successfully loading data from the server side with sorting and pagination functionality. However, I am attempting to sort only the items visible on the table instead of sorting from the server side. ...

Connecting an Angular 4 Module to an Angular 4 application seems to be causing some issues. The error message "Unexpected value 'TestModule' imported by the module 'AppModule'. Please add a @NgModule annotation" is

Update at the bottom: I am currently facing a massive challenge in converting my extensive Angular 1.6 app to Angular 4.0. The process has turned into quite a formidable task, and I seem to be stuck at a specific point. We have a shared set of utilities th ...

Having trouble with triggers: Unable to locate the module 'csv-parse/sync' for parsing

Currently, I am utilizing Firebase functions to create an API that is capable of parsing CSV files. However, whenever I attempt to utilize csv-parse/sync instead of csv-parse, my deployment to Firebase Functions encounters a failure with the subsequent er ...

What is the reason for the lack of compatibility between the TypeScript compilerOptions settings 'noEmitOnError: true' and 'isolatedModules: false'?

Whenever I try to execute TypeScript with isolatedModules set as true and then false, I keep encountering this error message: tsconfig.json(5,9): error TS5053: Option 'noEmitOnError' cannot be specified with option 'isolatedModules'. ...

NPM displaying an error message

npm ERROR! Windows_NT 6.3.9600 npm ERROR! Command "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\np ...

Image control failing to display SVG file

I am facing an issue with displaying an SVG file on the img control in angular10. When I try to use SVG, it's not showing up but it works fine when I change the file type to jpg for the same control. The img control is placed inside a nav bar. Here i ...

Utilizing Angular 16 to Link Component Input with Parent Route Parameter

Picture a scenario where there is a component (some.component.ts) in Angular 16 that retrieves the value for its foo property from activeRoute, specifically from the parent route. Take a look at the code snippet below: @Input() foo!: string; constructor(p ...

An issue was encountered when attempting to log out the user from Firebase

My website is built using the Ionic and Angular Frameworks along with Firestore database. The signout feature works as expected, but unfortunately, an error occurs when a user tries to sign out of their account. The error message: FirebaseError: Missing o ...