Ways to display components within the content section of the home component rather than on a distinct page using Angular 5

I recently started working with Angular 5 and I'm encountering an issue with component routing.

My goal is to have the app display a login screen when a user first opens it (the login screen should take up the entire browser window). Once the user successfully logs in, they should be directed to the Home Component.

The Home component includes a Toolbar and Side menu bar. When a user selects an option from the side menu bar, I want to show the relevant component data in the content area of the Home component.

Currently, everything is functioning as expected - the login screen is displayed initially and upon successful validation, the Home page is shown to the user.

The problem arises when a user selects a menu item from the side menu bar - instead of displaying the respective component in the content area of the Home component, it opens as a separate component that takes up the full screen.

home.component.ts

 <mat-sidenav-container class="sidenav-container">

      <mat-sidenav #drawer class="sidenav" fixedInViewport="true" [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
        [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="!(isHandset$ | async)" style="background:black">
        <mat-toolbar class="menuBar">Menus</mat-toolbar>
        <mat-nav-list>
          <a class="menuTextColor" mat-list-item routerLink="/settings">Link 1</a>
        </mat-nav-list>
      </mat-sidenav>

      <mat-sidenav-content>
        <mat-toolbar class="toolbar">
          <button class="menuTextColor" type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()"
            *ngIf="isHandset$ | async">
            <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
          </button>
          <span class="toolbarHeading">Application Title</span>
        </mat-toolbar>

//Content area ,need to show the components related to the side menu

      </mat-sidenav-content>

    </mat-sidenav-container>

app.components.ts

<router-outlet></router-outlet>

In app.component.ts, I have the

app.module.ts

const routings: Routes = [
    { path: '', redirectTo: '/login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    { path: 'home', component: HomeComponent },
    { path: 'settings', component: SettingsComponent },
    { path: '**', redirectTo: '/login', pathMatch: 'full' },
];

where I have defined the routes.

Can someone assist me in resolving this issue?

Answer №1

If you're looking to implement a child route in your application, here's what you need to do:

Ensure that both the home component and app component have a

<router-outlet></router-outlet>
. Then, create a new component to contain the content you want to replace in your main component.

<mat-sidenav-container class="sidenav-container">

  <mat-sidenav #drawer class="sidenav" fixedInViewport="true" [attr.role]= (isHandset$ | async) ? 'dialog' : 'navigation'"
    [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="!(isHandset$ | async)" style="background:black">
    <mat-toolbar class="menuBar">Menus</mat-toolbar>
    <mat-nav-list>
      <a class="menuTextColor" mat-list-item routerLink="/settings">Link 1</a>
    </mat-nav-list>
  </mat-sidenav>

  <mat-sidenav-content>
    <mat-toolbar class="toolbar">
      <button class="menuTextColor" type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      <span class="toolbarHeading">Application Title</span>
    </mat-toolbar>

    // Add the new component within the router-outlet tag
    <router-outlet></router-outlet>

  </mat-sidenav-content>

</mat-sidenav-container>

Next, update your routes as shown below:

const routings: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  {
    path: 'home',
    component: HomeComponent,
    children: [
      { path: '', component: NewComponent },
      { path: 'settings', component: SettingsComponent },
    ]
  },
  { path: 'login', component: LoginComponent },
  { path: '**', redirectTo: '/login', pathMatch: 'full' },
];

The route /home will remain the same visually, despite being wrapped by the new component. On the other hand, the route /home/settings will display your settings component inside the home component.

Answer №2

If you want to organize your app structure, consider implementing the following steps. First, create a app.component.html and app.component.ts. In your app.component.html, use the following code:

<app-header *ngIf=" this.session_data != null " ></app-header>
<mz-progress [backgroundClass]="'grey lighten-4'" *ngIf=" progress == true"></mz-progress>
<router-outlet></router-outlet>
<app-footer></app-footer>

This setup will display the header and footer on every page by default. You can also set conditions for specific pages, and those pages will be loaded under

<router-outlet></router-outlet>
.

You have the option to include your sidebar in the header or footer components as well. Create separate components for these elements and write HTML & .ts code accordingly.

In your header/sidebar.html file, add the following:

<div class="app-header" *ngIf="header == true">
//add your HTML content here
</div>

In your app.module.ts, load your AppComponent using:

bootstrap: [AppComponent],

Define your routes like this:

export const routes: Routes = [
   { path: '', component: LoginComponent, canActivate: [Guard1] },
   { path: 'dashboard', component: DashboardComponent, canActivate: [Guard] },
   { path: 'afterDashboard', component: AfterDashboardComponent, canActivate: [Guard, DateGuard] },
   { path: 'formlist', component: FormlistComponent, canActivate: [Guard, DateGuard] }
},
];

I hope this information helps you achieve what you are looking for.

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 could be causing the vue-property-decorator @Emit to malfunction in my Vue TypeScript file?

I am currently working with Typescript and Vuejs, where I have a child component called child.component.tsx import Vue from 'vue'; import Component from 'vue-class-component'; import { Emit } from 'vue-property-decorator'; ...

The 'ngModel' property cannot be bound to a 'textarea' element because it is not recognized as a valid property

When I run Karma with Jasmine tests, I encounter the following error message: The issue is that 'ngModel' cannot be bound since it is not recognized as a property of 'textarea'. Even though I have imported FormsModule into my app.modu ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...

FormArray in Angular2 can be nested inside another FormArray

I have the following code snippet: this.MainForm = this.fb.group({ MainArray: this.fb.array([ { ChildArray1: this.fb.array([]), ChildArray2: this.fb.array([]), } ]), }) Next, in my method, I have the following code: let MainArr ...

Verifying the eligibility of a value for a union type

In my app, there is a type called PiiType that enforces strong typing: type PiiType = 'name' | 'address' | 'email'; When receiving potentially sensitive information from the server, we need to verify if it aligns with this d ...

Dynamically binding button types with Angular Material

Incorporating Angular Material into my project has been a goal of mine. I am looking to dynamically set the button type based on a variable, but I am encountering some challenges. This is what I have attempted: export class ButtonComponent { type: ' ...

TSLint in TypeScript showing unexpected results

In the process of developing a project using Angular, I recently made the switch from VS Code to WebStorm. Unfortunately, I'm encountering some difficulties that I can't seem to make sense of. To ensure everything is functioning correctly, I perf ...

Monitor the closure of a programmatically opened tab by the user

Currently, I am in the process of developing a web application using Angular 11 that interacts with the msgraph API to facilitate file uploads to either onedrive or sharepoint, and subsequently opens the uploaded file in the Office online editor. Although ...

Combining several arrays to find the array of shared elements as the final result

In my JavaScript/TypeScript application built with Angular, I am facing the challenge of merging multiple arrays and extracting the common values that appear in all arrays. For example: arrayOne = [34, 23, 80, 93, 48] arrayTwo = [48, 29, 10, 79, 23] arrayT ...

The input 'Query' cannot be matched with the type '[(options?: QueryLazyOptions<Exact<{ where?:"

Using codegen, I've created custom GraphQL hooks and types. query loadUsers($where: UserFilter) { users(where: $where) { nodes { id email firstName lastName phoneNumber } totalCount } } export functio ...

Best practices for receiving messages from SQS in Node.js

I am exploring how to implement SQS in a similar manner as RabbitMQ or Kafka, where we usually set up a listener. However, after going through their documentation, I couldn't find any instructions on how to set up a listener for SQS: Currently, I am ...

Transferring Arrays in Angular: A Step-by-Step Guide

I am trying to assign one array to another orders = [ { 'id': PROCESSING, 'displayName': 'Processing' }, { 'id': SHIPPED, &apo ...

The program encountered an issue where it was unable to access the property 'ObjectTracker' because it was

I am relatively new to Angular development and I am attempting to incorporate into my Typescript Angular application. Even though I have included the type definitions, I am encountering an issue: MonitorComponent_Host.ngfactory.js? [sm]:1 ERROR TypeErr ...

Setting up ReactJS and TypeScript in a fresh MVC5 project from scratch

After extensively trying out various tutorials, I have yet to successfully run a basic MVC5 project using TypeScript and ReactJS. For reference, I have created these projects from scratch in Visual Studio 2015 with .NET 4.6.1, using the ASP.NET Web Applic ...

Using require() instead of import in Strip-Ansi leads to an exception being generated

Encountering an issue with my Angular 13 project when attempting to serve it, I am faced with the following error: An unhandled exception occurred: require() of ES Module C:\Users\username\Documents\project\builds\Production ...

Tips for closing a notification popup from the NzNotificationService

I'm currently utilizing NG-ZORRO Notification Here is my Angular code snippet: this.notif = this.notification.create( 'success', 'Notification', 'test message' ); I haven't been able to locate any API meth ...

Live reload functionality in Webpack is currently not functioning as expected when utilized with the Angular

Recently purchased a template that incorporates Angular. I diligently followed all the initial setup steps, but encountered an issue with live reloading once I started making changes to the project. It is also worth noting that the project utilizes Webpa ...

The latest version of Angular2 RC6 has removed the provide() function, so users will have to find a workaround to achieve the same functionality

I came across the following code from the book Mastering Angular 2 Components, but it seems to be incompatible with Angular 2 RC. The **provide()** function is no longer a part of angular/core in the current version. I really need this code to work: cons ...

Undefined Perception

Trying to obtain values from an observable, my subscription code within the component looks like this: this.checkoutService.getDisabledDate().subscribe (dates=>{this.formattedDate=dates}, (error:any)=>{console.log(error)}); When logging this.forma ...

Numerous items lined up in a single row

I have designed a skills section that includes a name and corresponding image. Now, I would like to pass the skill's name into a child component. My goal is to display three of these skills on the same row, but using ngFor currently results in each sk ...