Leverage the power of Angular 17 by implementing standalone functionality through the utilization of multiple components

As someone who is currently self-studying HTML and proficient in CSS and JS, with the ability to use Bootstrap, I am venturing into using front-end frameworks for the first time. English is my second language.

Angular CLI: 17.3.3
Node: 20.11.1
Package Manager: npm 10.2.4

Upon researching, I discovered that Angular 17 is components based.

My objective is to build a single-page application consisting of 5 pages. Each page will have 5 or 6 different parts such as paragraphs, tables, cards, etc., all sharing the same header and footer.

To simplify, let's say I plan to create an SPA with:

  2-a. two pages
  2-b. each page containing two different paragraphs - totaling four paragraphs
  2-c. shared header and footer

I have learned how to create the shared header and footer, as well as how to make the navbar functional by routing each tab to a specific component.

The issue at hand: I aim to create separate components for each paragraph, resulting in a total of four components (two for each page).

How can I configure the router to display two different components (c1, c2 on the first page, and c3, c4 on the second page) within one page?

Answer №1

If you want to group two components together and display them using routing in Angular, you can create a wrapper component that contains these two components. The wrapper component is necessary for routing purposes. Take a look at the following example code to see how this can be achieved:

import { Component } from '@angular/core';
import { RouterModule, provideRouter } from '@angular/router';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { OneComponent } from './app/one/one.component';
import { TwoComponent } from './app/two/two.component';
import { ThreeComponent } from './app/three/three.component';
import { FourComponent } from './app/four/four.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterModule],
  template: `
    <a [routerLink]="['group1']">group 1 </a> | 
    <a [routerLink]="['group2']">group 2 </a>
    <br/>
    <router-outlet/>
  `,
})
export class App {
  name = 'Angular';
}

@Component({
  selector: 'wrapper1',
  standalone: true,
  imports: [OneComponent, TwoComponent],
  template: `
    <app-one/>
    <app-two/>
  `,
})
export class WrapperComponent {
  name = 'Angular';
}

@Component({
  selector: 'wrapper2',
  standalone: true,
  imports: [ThreeComponent, FourComponent],
  template: `
    <app-three/>
    <app-four/>
  `,
})
export class Wrapper2Component {
  name = 'Angular';
}

bootstrapApplication(App, {
  providers: [
    provideRouter([
      {
        path: 'group1',
        component: WrapperComponent,
      },
      {
        path: 'group2',
        component: Wrapper2Component,
      },
      {
        path: '**',
        redirectTo: 'group1',
        pathMatch: 'full',
      },
    ]),
  ],
});

Check out the StackBlitz Demo to see it in action!

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

Retrieve a specified number of child elements

In my database, I have two tables: Blog and Post. Each blog can have multiple posts associated with it. My goal is to retrieve a blog along with its corresponding posts, but I only want to fetch blogs that have exactly 4 posts. Additionally, I need to map ...

Angular 2: The Power of Import Statements

Is it necessary to re-import ElementRef in a service if it has already been imported in the app module? Alternatively, is it possible to import all elements from angular/core in the app.module and have them accessible to all directives, pipes, and service ...

Displaying Local Storage Data in Primeng Dropdown

I'm looking to implement local storage for the selected dropdown option, allowing users to see the same selection when they reload the page. Here's my dropdown: <p-dropdown [options]="languages" [(ngModel)]="selectedLanguage ...

Using Froala events in Angular 2: A guide

Currently, I am incorporating Froala into my Angular 2 project. I have managed to upload an image successfully but am encountering issues triggering the image.uploaded event. The Froala document provides an example of how the event should be implemented: ...

Angular 5 - Issue with ngModel not binding correctly to tinymce editor

I have successfully integrated TinyMCE into my Angular 5 project, but I am facing an issue with data binding. How can I achieve data binding with TinyMCE in my Angular 5 project? Specifically, I am trying to bind the TinyMCE text editor with ngModel, but ...

Is there a way to check if a date of birth is valid using Regular Expression (RegExp) within a react form?

const dateRegex = new RegExp('/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.] (19|20)\d\d+$/') if (!formData.dob || !dateRegex.test(formData.dob)) { formErrors.dob = "date of birth is required" ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...

Having trouble with implementing a custom hook in React using Typescript?

Having difficulty with typing in the following Hook: import { SetStateAction, useCallback, useEffect, useRef, useState } from 'react'; type Callback<T> = (value?: T) => void; type DispatchWithCallback<T> = (value: T, callback?: Ca ...

Converting JSON objects into TypeScript classes: A step-by-step guide

My challenge lies in converting Django responses into Angular's User array. This conversion is necessary due to variations in variable names (first_name vs firstName) and implementing specific logic within the Angular User constructor. In simple term ...

Can you provide a guide on setting up and utilizing mathlive within NuxtJS?

Can anyone assist me? I am trying to figure out why my code is not working or if I have implemented it incorrectly. I used npm i mathlive to obtain input. However, following the instructions for implementing nuxt plugins in the documentation has not yield ...

Creating an Angular component to display a dynamic table using ngFor directive for a nested JSON data structure

Currently diving into Angular (version 8) and grappling with the following JSON structure {layer1 : [ { id: 'lay1', name: 'first layer', results: [ { rows: ...

What is the reason behind TypeScript failing to provide type safety in a generic higher order component which introduces extra properties into React components?

I'm currently working on developing a versatile higher order component, but have encountered an issue with type safety not being enforced. Interestingly, when attempting the same implementation without using generics, the type safety is verified as ex ...

Can you point me to the definition of pausesLocationUpdatesAutomatically in Swift 5?

As I develop my standalone WatchOS application that utilizes CoreLocation, I encountered an issue regarding ensuring continuous location updates. Apple's definition of pausesLocationUpdatesAutomatically can be found here, however, I discovered that th ...

Pause and anticipate the occurrence of AdMob's complimentary video reward event within a defined function in Ionic/Typescript

In my ionic app, I have a function that determines if the user has watched a reward video to access another function: let canUseThisFunction = await this.someService.canUseFunction(); if(canUseThisFunction){ console.log("can use"); } else { cons ...

Incorporate a script into your Angular-CLI project

Can you guide me on inserting a script file into the index file of an angular2 project that was generated using angular-cli? : <!doctype html> <html> <head> <meta charset="utf-8"> <title>MyAngularApp</title> ...

how to navigate to a different page programmatically upon selecting an option in the side menu

ionic start mySideMenu sidemenu --v2 After creating a sidemenu using the code above, I implemented some login-logout functionality by storing user details in a localStorage variable named "userDetails". When clicking on the logout option from the sideme ...

Having trouble uploading big files on your Windows system?

My challenge is to successfully upload a large file using Angular. Specifically, I am attempting to upload a Human Genome tar file, which is a minimum of 2.5gb in size. Strangely, when I try to upload the file from Linux using any browser such as Chrome or ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

Is it acceptable to include a @types library as a regular dependency in the package.json file of a Typescript library?

Should the library also be compatible with Typescript projects? I am developing a Typescript library that utilizes node-fetch and @types/node-fetch, which will be shared through an internal NPM registry within the company. If I only include @types/node-f ...

Angular components can be modified and concealed

I am facing an issue with a page that contains 3 components loaded. (See image below) Whenever I click on Component 3, it switches to Component 4. Then, clicking on Component 4 should switch to Component 5 while also hiding/removing Component 2. How can I ...