Trouble accessing nested components in Angular CLI beyond the first level of components

I'm diving into Angular CLI for the first time and trying to recreate a previous web project of mine. I've managed to nest and display components inside the root component successfully, but after that, I'm facing issues referencing any component in the HTML.

Here's an overview of my code:

index.html

<!doctype html>
  <html lang="es">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Testing Angular</title>
      <base href="/">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body>
      <app-root></app-root>
    </body>
  </html>

app.module.ts

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

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { FirstComponent } from './first/first.component';

@NgModule({
  declarations: [AppComponent, FirstComponent],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

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

export class AppComponent {}

app.component.html

<section id="container">
  <app-first></app-first>
</section>

<router-outlet></router-outlet>

first.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SecondComponent } from './second/second.component';

@NgModule({
  declarations: [SecondComponent],
  imports: [CommonModule]
})
export class FirstModule { }

first.component.ts

import { Component } from '@angular/core';

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

export class FirstComponent {}

first.component.html

<div id="first">
  <app-second></app-second> <!-- This gives an error: it doesn't know whats Second Component -->
</div>

second.module.ts

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

@NgModule({
  imports: [CommonModule],
  declarations: []
})
export class SecondModule { }

second.component.ts

import { Component } from '@angular/core';

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

export class SecondComponent {}

second.component.html

<div id="second">
  <span>I'm second component!</span>
</div>

The

<app-second></app-second>
reference is causing errors. It's not even showing up in the suggestions list on Visual Studio Code.

Answer №1

Make sure to include your modules in the right place, as Angular itself is not aware of your SecondComponent. You need to add either FirstModule or SecondModule to your AppModule. Refer to the Angular documentation for more guidance here

  imports: [BrowserModule, AppRoutingModule, FirstModule],

Remember to update your FirstModule by including exports with components you wish to make available to other modules.

exports: [SecondComponent] 

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

Angular: Redirecting to destination that necessitates initial visit to the login page

One common UX strategy involves saving a user's desired URL when their navigation fails due to requiring re-login. The app then navigates to that saved URL once the user successfully logs in. When it comes to implementing this feature in Angular, my i ...

How can I prevent event propagation in Vuetify's v-switch component?

Currently, I am working with Vuetify and have incorporated the use of v-data-table. Whenever I click on a row within this data table, a corresponding dialog box represented by v-dialog should open. Additionally, each row contains a v-switch element. Howeve ...

Joomla website experiencing issues with Bootstrap popover functionality

Just wanted to share that I am currently working on this page: I found an example that inspired me from here: I have a feeling that Joomla might be including a resource that is causing conflicts with the popover not showing. This is the code snippet I h ...

Adding android to the ionic platform leads to the subsequent error message

I am currently facing an issue while attempting to integrate the Android platform into my Ionic 2 project. The error message I'm encountering is as follows: Error: Cannot find module 'internal/util/types' at Function.Module._resolveFilename ...

How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c =&g ...

Nock is capturing my request, however, my AJAX call is encountering an error

I am currently conducting a test on an AJAX request using the XMLHttpRequest method: export default function performTestRequest() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/service'); xhr.onload = ( ...

I'm having an issue where I'm trying to post form data using AJAX, but for some reason, the form continues to submit and refresh the page. Can anyone

Recently, I have been working on a small and simple chat application using mainly JQuery and AJAX technologies. Below is the HTML form I have created for this chat application: <form class="chat_form" method="post" id="chat_form" autocomplete="off"> ...

Steps for automatically adding a new user to the AddThis service for configuring analytics services

As I work on creating a Backoffice for my website, I am looking to provide a mobile version for all users uniformly. To enhance user experience, I plan to introduce a "Report" tab in the back office interface. This tab will display analytics information g ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

Local directory system for organizing users' files and folders

My website is built using mean-stack technology. I utilize the File System to create folders and write files on servers. Here is an example of the backend code: router.post('/httpOnly/mkdir', function (req, res, next) { var fs = require(&apo ...

Exploring smooth scrolling functionality using AngularJS and integrating it with IFrames

After implementing an angular controller, I included the following code: angular.element(document).ready(function () { ... } Within this setup, I added a function to enable smooth scrolling to the hash of window.location.hash using .animate({scrollTop... ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

Avoid unnecessary re-renders in React Redux by ensuring that components do not update when properties are not utilized in their

I'm encountering an issue with a component that keeps re-rendering. I've implemented Redux to handle my states. Within a component, I access a property (isPlaying: bool) from the state using mapStateToProps in various methods of the component, ex ...

Parsing JSON objects with identifiers into TypeScript is a common task in web development

I possess a vast JSON object structured like so: { "item1": { "key1": "val1", "key2": "val2", "key3": [ "val4", "val5", ] }, { "item2": { "key1": "val1", "ke ...

The jQuery ajax function is not properly displaying or hiding the loader div

While attempting to call PHP code using a jQuery AJAX function, I encountered an issue where I wanted to display a loader div while the request was being sent and then hide the div once the request was complete. To simulate this scenario, I deliberately de ...

A problem has occurred in Next.js where FileReader is not recognized and is causing a Reference

Exploring the latest features of Next.js 13 with the /app directory, I encountered an issue while using the FileReader in a basic client-side component that manages an input form. Here is a brief overview of the code: "use client"; import React, ...

Refresh selected items after inserting data via ajax in CodeIgniter

I have a select list on my view that allows users to add new items using a plus button. However, when a new item is added, the list does not refresh. I don't want to refresh the entire page with an ajax query. Instead, I am trying to implement a metho ...

Error encountered when transitioning to TypeScript: Unable to resolve '@/styles/globals.css'

While experimenting with the boilerplate template, I encountered an unusual issue when attempting to use TypeScript with the default NextJS configuration. The problem arose when changing the file extension from .js to .tsx / .tsx. Various versions of NextJ ...

Collaborate on an Angular2 codebase for both a web application and a hybrid application

I am considering creating a mobile app based on my existing Angular2 web app codebase. After researching, I have found two possible options - Ionic2 and NativeScript. Upon further investigation, it appears that both Ionic2 and NativeScript have their own ...