Incorporating a Component with lazy-loading capabilities into the HTML of another Component in Angular 2+

Striving to incorporate lazy loading in Angular 2, I have successfully implemented lazy loading by following this helpful guide. Within my application, I have two components - home1 and home2. Home1 showcases the top news section, while home2 is dedicated to listing other news articles. Initially, only home1 is displayed to the user. Upon scrolling, I aim to load home2 within home1 (similar to calling a partial view in MVC).

I attempted to call home2 within home1 using

<app-home2-list></app-home2-list>
, but encountered an error in the process.

https://i.sstatic.net/XBe4z.png

I am unsure of the correct method to call the home2 HTML within the home1 HTML. Are there alternative approaches available to achieve this integration?

Within my app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { MenuComponent } from './menu.component';
import { HomeComponent } from './home/home.component';
import { Const_Routing } from './app.routing';
import { HttpModule } from '@angular/http';
import { Home2ListComponent } from './home2/home2-list/home2-list.component';
import { Home1ListComponent } from './home1/home1-list/home1-list.component';



@NgModule({
  declarations: [
    AppComponent,
    MenuComponent,
    HomeComponent,
    Home1ListComponent,
    Home2ListComponent
  ],
  imports: [
    BrowserModule,
    Const_Routing,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Details regarding home1-list.component.ts and home2-list.component.ts (both codes are identical, with differing API calls):

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { ViewEncapsulation } from '@angular/compiler/src/core';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';
import '../../../assets/scripts/endlessriver.js';
import * as $ from 'jquery';
import { SharedService } from '../../Services/shared.service';
import { Home1Service } from './home1.service';
import { Home2ListComponent } from '../../home2/home2-list/home2-list.component';

declare var jQuery: any;

@Component({
  selector: 'app-home1-list',
  templateUrl: './home1-list.component.html',
  styleUrls: ['./home1-list.component.css','../../../assets/styles/common.css','../../../assets/styles/endlessriver.css'],
  providers: [Home1Service,SharedService]
})
export class Home1ListComponent implements OnInit {

  constructor(public Service: Home1Service,public CommonService:SharedService) { }

  @ViewChild('marqueeID') input: ElementRef;

  HomeList:any;
  HomeList1:any;
  HomeList2:any;
  HomeList3:any;
  sectionName:string;
  datetime:string;
  productId:number=2;
  getListingData(sectionName)
  {
              this.Service.getListingNews(sectionName,15).subscribe(
                  data => {
                      this.HomeList = data.map(e => {
                          return { SectionName:e.ChildName,ArticleId:e.ArticleId, HeadLine: e.HeadLine, Abstract: e.Abstract, ImageLink: e.ImageLink ,UpdatedDate:this.CommonService.getDateFormat(new Date(e.UpdatedDate),'others').toString()};
                      })
                  },
                  error => { console.log(error) });
                  this.Service.getListingNews("world",5).subscribe(
                    data => {
                        this.HomeList1 = data.map(e => {
                            return { Heading:'world',SectionName:e.ChildName,ArticleId:e.ArticleId, HeadLine: e.HeadLine, Abstract: e.Abstract, ImageLink: e.ImageLink ,UpdatedDate:this.CommonService.getDateFormat(new Date(e.UpdatedDate),'others').toString()};
                        })
                    },
                    error => { console.log(error) });
                    this.Service.getListingNews("national",5).subscribe(
                        data => {
                            this.HomeList2 = data.map(e => {
                                return {Heading:'national', SectionName:e.ChildName,ArticleId:e.ArticleId, HeadLine: e.HeadLine, Abstract: e.Abstract, ImageLink: e.ImageLink ,UpdatedDate:this.CommonService.getDateFormat(new Date(e.UpdatedDate),'others').toString()};
                            })
                        },
                        error => { console.log(error) });
                        this.Service.getListingNews("state",5).subscribe(
                            data => {
                                this.HomeList3 = data.map(e => {
                                    return { Heading:'state',SectionName:e.ChildName,ArticleId:e.ArticleId, HeadLine: e.HeadLine, Abstract: e.Abstract, ImageLink: e.ImageLink ,UpdatedDate:this.CommonService.getDateFormat(new Date(e.UpdatedDate),'others').toString()};
                                })
                            },
                            error => { console.log(error) });
  }
  getHomeList(name: string) 
  {
    if(name=="0")
    {
      return this.HomeList1;
    }
    else if(name=="1")
    {
      return this.HomeList2;
    }
    else
    {
      return this.HomeList3;
    }
  }

  ngOnInit() {
      this.datetime=this.CommonService.getDateFormat(new Date(),'home').toString();
    this.getListingData('TopNews');
  }

  ngAfterViewInit() {

    jQuery(this.input.nativeElement).endlessRiver({

    });
    $( document ).ready(function() {
        $('.brkngBody').show();
    });
  }
}

Information regarding home1.module.ts:

Information regarding home2.module.ts:

Information regarding home1-routing.module.ts:

Demo

Answer №1

Check out the code snippet below:

//module1.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { Module1RoutingModule } from './module1-routing.module';
import { Module1ListComponent } from './module1-list/module1-list.component';

@NgModule({
  imports: [
    CommonModule,
    Module1RoutingModule
  ],
  exports:[Module1ListComponent],
  declarations: [Module1ListComponent]
})
export class Module1Module { }

//Module2.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { Module2RoutingModule } from './module2-routing.module';
import { Module2ListComponent } from './module2-list/module2-list.component';
import { Module1ListComponent } from '../module1/module1-list/module1-list.component';
import { Module1RoutingModule } from '../module1/module1-routing.module';
import { Module1Module } from '../module1/module1.module';

@NgModule({
  imports: [
    CommonModule,
    Module2RoutingModule,
    Module1ListComponent
  ],
  exports:[
    Module2ListComponent
  ],
  declarations: [Module2ListComponent]
})
export class Module2Module { }

DEMO

Answer №2

In case your Home2 component is located in a different module, you will need to include it in the "exports" block. This will enable you to utilize the component within the Home1 module.

For example:

Module 1

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

    @NgModule({
      imports: [
        CommonModule
      ],
      declarations: [Home1Component],
      exports: [Home1Component]
    })
    export class Module1 { }

Module 2

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';    
@NgModule({
      imports: [
        CommonModule
      ],
      declarations: [Home2Component],
      exports: [Home2Component]
    })
    export class Module2 { }

AppModule

 @NgModule({
      imports: [
        CommonModule,
        Module1,
        Module2
      ],
      declarations: [],
      exports: []
    })
    export class AppModule { }

Answer №3

If you encounter this issue, make sure to include your component class name in the "imports" section of the @NgModule in the AppModule.

For instance, if your component class is called home1 and declares the selector app-home2-list.

app/home2.component.ts

import { Component} from '@angular/core';
@Component({
  selector: 'app-home2-list',
  templateUrl: 'app/home2.component.html',
  styleUrls: ['app/mycomponent.css']
})
export class Home2{ // Component code goes here}

app/home1.component.ts

import { NgModule, Component, enableProdMode } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
// Include the reference to the component to use the selector in the template 'app.component.html'
import { Home2} from './home2.component';

if(!/localhost/.test(document.location.host))
{
    enableProdMode();
}

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

export class Home1Component{ // App component code goes here}

@NgModule({
  imports: [
    BrowserModule,
    MyComponentModule
  ],
  declarations: [Home1Component],
  bootstrap: [Home1Component, Home2Component]})

export class AppModule { }

platformBrowserDynamic().bootstrapModule(AppModule);

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 best practice for passing parameters to a child uiView in AngularJS?

I am working on a project with multiple states and views. angular.module('myapp', ['ui.router']).state('property', { url: '/property', views: { '': { templateUrl: 'partial/ ...

How can I display and link a base64 string to an Image as a source in Nativescript?

I'm having trouble displaying and binding a base64 image as an ImageSource in my View. The image doesn't show up at all, and I couldn't find any helpful information about it in the documentation. Am I missing something? The imageSource prop ...

Error: The specified module 'tty' was not found in the directory '/workspace/node_modules/pace/node_modules/charm'

My attempt to compile my frontend project using ng build resulted in the following error message: ERROR in ./node_modules/pace/node_modules/charm/index.js Module not found: Error: Can't resolve 'tty' in '/workspace/node_modules/p ...

The Primeng badge feature fails to detect changes in severity

Within my primeng application, there is an icon featuring a badge that is structured as follows: <i (click)="showAllNotifications()" class="pi pi-bell mr-3 p-text-secondary" pBadge style="font-size: 2rem" [value]=&q ...

"Unlocking Angular event intellisense in Visual Studio Code: A Step-by-Step Guide

Currently, I am enrolled in an Angular course on Udemy. The instructor prefers using VS Code as his code editor, and one interesting feature he showcased was when he tried to add events to a button element. As soon as he opened the parenthesis after the bu ...

Symfony seems to be dropping my session unexpectedly during certain requests

Currently dealing with angular 2, I am encountering issues with requesting symfony where certain requests cause the sessions to be lost. Strangely enough, some requests work perfectly fine while others do not. If anyone has any insight or advice on what co ...

Unable to locate the name 'JSON' in the typescript file

I have been working on an angular application where I have implemented JSON conversion functionalities such as JSON.stringify and JSON.parse. However, I encountered an error stating 'Cannot find name 'JSON''. Furthermore, there is anoth ...

The Interface in TypeScript will not function properly when used on a variable (Object) that has been declared with the value returned from a function

I am currently in the process of developing an application using Ionic v3. Strangely, I am encountering issues with my interface when trying to assign a variable value returned by a function. Here is an example that works without any problems: export int ...

Tips for creating a personalized asynchronous Express handler that seamlessly receives specific typed parameters

In my quest to create a unique Express endpoint wrapper, I aim to wrap async functions and handle errors effectively. The current implementation is basic but functional: import type {Request, RequestHandler, Response} from 'express'; type Handle ...

The API functions seamlessly with TypeScript, however, during the transpilation process, it fails to locate the model

I am in the process of developing a straightforward API that is capable of Creating, Reading, and Deleting student information within a postgres database. Interestingly, I have encountered an issue when using ts-node-dev without transpiling the files to J ...

Tips on sorting a FileList object selected by a directory picker in JavaScript/TypeScript

I need to filter or eliminate certain files from a FileList object that I obtained from a directory chooser. <input type="file" accept="image/*" webkitdirectory directory multiple> Within my .ts file: public fileChangeListener($event: any) { let ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

Encountering a Typescript issue while utilizing day classes from Mui pickers

Recently, I encountered an issue with my code that alters the selected day on a Mui datepicker. I came across a helpful solution in this discussion thread: MUI - Change specific day color in DatePicker. Although the solution worked perfectly before, afte ...

What is the proper way to utilize bootstrap dropdown menus?

I need to create a dropdown menu similar to the one shown in this image: https://i.sstatic.net/SXDgy.png https://i.sstatic.net/wVbnd.png I attempted to use code from the following URL: https://getbootstrap.com/docs/4.0/components/dropdowns/, but unfortun ...

What are the top techniques for designing with Angular 2 Material Design?

As a newcomer to angular 2 material design, I have noticed the primary, accent, and warn classes that apply specific colors to elements. Are these the only styling options available in Angular Material 2? Are there other classes that can be utilized for cu ...

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...

Oops! An unhandled promise error occurred when trying to fetch a URL with a status of 0. The response received has a status code of

I keep encountering an error whenever I try to hit a post request URL: Error: Uncaught (in promise): Response with status: 0 for URL: null at c (http://localhost:8100/build/polyfills.js:3:19752) at c (http://localhost:8100/build/polyfills.js:3:1 ...

The attribute 'tableName' is not found within the 'Model' type

Currently in the process of converting a JavaScript code to TypeScript. Previously, I had a class that was functioning correctly in JS class Model { constructor(input, alias) { this.tableName = input; this.alias = alias; } } Howev ...

Combine iron-page and bind them together

Recently, I've started learning about Polymer and I want to bind together paper-tabs and iron-pages so that when a tab is clicked, the content loads dynamically. After going through the documentation, this is what I have tried: <app-toolbar> ...

Encountering a 403 error when attempting to upload files to Google Cloud Storage (GCS) using Signed URLs

The main aim is to create a signed URL in the api/fileupload.js file for uploading the file to GCS. Then, retrieve the signed URL from the Nextjs server through the nextjs API at localhost://3000/api/fileupload. Finally, use the generated signed URL to upl ...