javascriptangularangular-standalone-components

Angular standalone component not rendering


I'm using Angular 19 and my version of node is 18.2. I've got an existing module project and have added a stand alone component. The issue I'm having is that the component does render and the constructor, ngOnInit, and ngAfterViewInit do not fire. The stand alone component also does not appear in the browser dev tools. Any idea what could be causing angular to not render this component?

Component: import { Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-lu-map2',
  standalone: true,
  imports: [],
  templateUrl: './lu-map2.component.html',
  styleUrl: './lu-map2.component.css',

})
export class LuMap2Component implements OnInit{
  constructor(){
    console.log("Constructor Fired");
  }

  ngOnInit() {
   console.log("message from lu-map2: OnInit Fired")
  }
  ngAfterViewInit() {
    console.log("message from lu-map2: ngAfterViewInit Fired")
   }

}

Component template:

<p>lu-map2 works!</p>

app.component template

<app-lu-map2></app-lu-map2>

if I swap out the standalone component with a non-standalone component it renders fine. Also see the attached screen shot that shows the component in the project, but the component is not is not listed in edge dev tools sources. (Doesnt appear in chrome or firefox either)


Solution

  • Did you import the LuMap2Component class in the imports array of your app.component's module (considering app.component is not standalone) or in the imports array of your app.component (considering the case where app.component is standalone) i.e.

    imports: [LuMap2Component]

    standalone components must first be imported in the modules or other standalone components before they can use them.

    Example of importing a standalone component in a module which will make the component available to other components declared in the same module:

    import {LuMap2Component} from './lumap2/lumap2.component';
    
    @NgModule({
        ....
       imports: [LuMap2Component]
        ....
    })
    export class AppModule { }
    

    Example of importing a standalone component in another standalone component which will make the imported standalone component available in the component that imports it.

    import {LuMap2Component} from './lumap2/lumap2.component';
    
    @Component({
       // Import the `LuMap2Component` component in
       // order to use it in this component's template.
       ...
       imports: [LuMap2Component],
       ... 
    })
    export class AppCompponent { }
    

    More on using standalone components here. Also you should follow the advice from the comment and import the CommonModule in LuMap2Component although this most likely is not the core issue of why you component isn't getting rendered.