Exploring Angular 2: Incorporating multiple HTML pages into a single component

I am currently learning Angular 2 and have a component called Register. Within this single component, I have five different HTML pages. Is it possible to have multiple templates per component in order to navigate between these pages? How can I implement routing while keeping each page's HTML and SCSS separate? That is my main goal.

Right now, I am using ngIf to render the pages, but this has made my code quite lengthy. Are there any alternative approaches to achieve the same functionality?

<!--View 1-->
        <div class="open-card-BG" *ngIf="registerView=='regView1'">
Register Page 1
</div>
            <!--View 2-->
            <div class="open-card-BG" *ngIf="registrationView=='regView2'">
Register Page 2
</div>


    @Component({
      selector: 'register-page',
      templateUrl: './register-page.component.html',
      styleUrls: ['./register-page.component.scss'],
      providers : [RegisterService,Configuration,LocalStorageService]
    })
        ngOnInit() {
        this.registerView= "regView1";
      }

    changeView(view) {

          this.registerView= view;
      }

      previousView(view) {

          this.registerView= view;
      }

Answer №1

Here is a suggested code snippet:

@Component({
    selector: 'register-page',
    template: `
            <div class="open-card-BG" *ngIf="registerView == 'regView1'">Reg View 1 Content</div>
            <div class="open-card-BG" *ngIf="registerView == 'regView2'">Reg View 2 Content</div>
            `,
    styleUrls: ['./register-page.component.scss'],
    providers: [RegisterService, Configuration, LocalStorageService]
})

export class Appcomponent {
    registerView = 'regView1';
}

Alternatively, you can try this approach:

page1.component.html

<div>
    <h1>Page1 Component Content</h1>
</div>

page2.component.html

<div>
    <h1>Page2 Component Content</h1>
</div>

home.component.html

<div>
    <div class="open-card-BG" *ngIf="registerView == 'regView1'">
         <app-page1-component></app-page1-component>
    </div>
    <div class="open-card-BG" *ngIf="registerView == 'regView2'">
         <app-page2-component></app-page2-component>
    </div>
</div>

component.ts

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})

export class HomeComponent {
    registerView = 'regView1';
}

Answer №2

To handle this situation, consider using *ngIf as it is the most practical approach. When you find yourself relying heavily on *ngIf to manage large sections of HTML, it may be a sign that these elements should actually be separated into distinct components due to their differing visual requirements.

If you notice common functionality across your .ts files, creating a base class with shared logic and then utilizing class inheritance in your individual components can help streamline your code organization.

export class BaseComponentLogic implements OnInit {

    ...

}

@Component({...})
export class MyFirstComponent extends BaseComponentLogic implements OnInit {

   ...
}

@Component({...})
export class MySecondComponent extends BaseComponentLogic implements OnInit {

   ...
}

Answer №3

When working with Angular, components represent a specific area of the interface and should have a single template associated with them. However, if you need to have multiple templates for a single component class, it is not considered standard practice in component definition. In such cases, you can create a base class and then extend this base class to create 3 separate components.

Answer №4

To simplify your component logic and display them on a single HTML file using the ngIf directive instead of multiple HTML files, you can follow these steps:

 import { Component, OnInit } from '@angular/core';
 import {Router, ActivatedRoute, Params} from '@angular/router';
 
 @Component({
   selector: 'app-registration',
   templateUrl: './registration.component.html',
   styleUrls: ['./registration.component.css']
 })
 export class RegistrationComponent implements OnInit {
 
   constructor(private activatedRoute: ActivatedRoute) { }
 
   abcde:string='';
 
   ngOnInit(): void {
     //fetch query string and set value of variable
     this.activatedRoute.queryParams.subscribe(params => {
         this.abcde=params['xyz'];
     });
   }
 }

In the HTML file, use the following ngIf directives:

<div *ngIf="abcde=='1'"> your content for case 1 </div>
<div *ngIf="abcde=='2'"> your content for case 2 </div>
<div *ngIf="abcde=='3'"> your content for case 3 </div>

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

The Element is Unfamiliar - Application with Multiple Modules

I seem to be facing an issue with how my modules are structured, as I am unable to use shared components across different modules. Basically, I have a Core module and a Feature module. The Core module contains components that I want to share across multip ...

Strategies for extracting information from the database

I have a pre-existing database that I'm trying to retrieve data from. However, whenever I run a test query, it always returns an empty value: { "users": [] } What could be causing this issue? entity: import {Entity, PrimaryGeneratedColumn, Col ...

Determine the overall sum of all items

Utilizing data fetched from my SQLite database, I'm utilizing *ngFor to display a comprehensive list of items with their respective names, prices, amounts, and totals. How can I calculate the grand total and display it at the bottom of the list? chec ...

Is there a way to transfer data to a different component in React without relying on a hierarchical parent-child relationship?

I am struggling to pass the data from the "SearchingData" Component to the "Search" Component. The SearchingData component is a child of the Search component. I need to transfer the data from the variable named "datacame" to the Search Component. Can som ...

AADSTS9002326: Token redemption across origins is only allowed for the client type of 'Single-Page Application'. Origin of request: 'capacitor://localhost'

My Ionic application is having trouble authenticating in Azure. I followed the guidance from a stackoverflow thread: Ionic and MSAL Authentication Everything went smoothly except for iOS, where I encountered the following error: AADSTS9002326: Cross ...

Utilizing PrimeNG TabView to automatically open a tab based on the URL

I have implemented PrimeNG's TabView component with three tabs - Home, Appointments, and Orders. In the Appointments and Orders tabs, there are lists of links that lead to individual appointment or order pages, which open as separate routes/pages out ...

The error message "TypeError: this.subQuery is not a function" is displayed

Whenever I execute the tests using jest, I consistently encounter the error message TypeError: this.subQuery is not a function pointing to a specific line in the testModelDb.test.ts file. In the tests/jest.setup.ts file: import 'reflect-metadata&apos ...

ngx-translate handling special characters problem

I'm currently working on an angular 4 project where I've implemented ngx-translate. I've encountered an issue with special characters such as à, which are displaying as ?. Do I need to use a specific method to properly translate these spec ...

Tips for extracting individual fields from a payload in Angular 8

How do I extract individual fields from the payload and bind them with HTML on a page? I am trying to retrieve the alphacode and countryname in Angular 8. This is my Component: this.table$ = this.productService.get(id) .map(actions => { c ...

Exploring Custom Validator Comparisons in Angular

Having trouble comparing two input values in a custom validator. An error should occur if the minValue exceeds the maxValue. FormGroup: sumFormGroup = this.formBuilder.group({ from: ['', [Validators.min(0), sumValidator]], to: [&ap ...

Using Class as a Parameter

I recently started using TypeScript and encountered an implementation issue. I'm working on a class that takes another class as an argument. The challenge is that it can be any class, but I want to define certain possible class properties or methods. ...

Could you tell me the kind of theme used in Material-UI version 5?

I've decided to switch my project over to MUI version 5 and embrace the use of emotion CSS. It's come to my attention that I need to incorporate the theme property, but now TypeScript is prompting me for a type definition for it. The current code ...

What is the method for retrieving an attribute's value from an object that does not have key-value pairs?

My current project involves working with dynamoose and running a query that produces the following output: [ Document { cost: 100 }, lastKey: undefined, count: 1, queriedCount: undefined, timesQueried: 1 ] When I use typeof(output), it returns O ...

Managing multiple asynchronous requests through Observables in web development

I am working on an Angular2 website that sends multiple ajax requests using Json Web Tokens for authorization when it is initialized Here are two examples: public getUser(): Observable<User> { // Code block to get user data } public getFriends ...

Ensuring precise type inference in generic functions using the keyof keyword

I am facing a challenge in creating a versatile function that accepts an object and a key from a specific subset of keys belonging to the type of the object. These keys should correspond to values of a specified type. This is how I attempted to implement ...

Nested REST API calls in Angular are causing only the inner call to be returned

When retrieving a ShoppingCart with ShoppingCartItems through an outer REST call, an Observable of the ShoppingCartItems is then used to make an inner call in order to enhance the items with a Provider. After the inner call, a tap(console.log) shows that ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

Automatically update the cart count in the header component in Angular 6 when a product is added to the cart, without the need to

I am working on an E-Commerce application using Angular 6. I am facing an issue with updating the shopping cart count in the header component whenever a product is added or removed from the cart. The cart count only updates when I refresh the page. I have ...

Access a PDF document in a new tab and save it with a specific file name using Angular

I am facing a challenge in Angular where I want to open a PDF file in a new tab and enable the user to download it with a specific name (Example.pdf). The current code successfully downloads the PDF but does not open a new tab (target=_blank is ineffecti ...

Struggling to resolve Docker freezing during the "RUN npm run build" step while working with Angular 15?

I am facing an issue while attempting to create a Dockerized Angular 15 project. The build process always seems to hang at the RUN npm run build step and never finishes. This is a fresh installation using ng new ng-sandbox-15, with the Dockerfile, .dockeri ...