How to import not standalone components to a standalone component in Angular 14+ [duplicate]
Asked Answered
M

1

12

I would like to know how to import a non-standalone component into a standalone component, given that the non-standalone component is being declared in an ngModule.

Malorie answered 6/1, 2023 at 14:15 Comment(0)
G
9

There's a section of the migration documentation about this exact use case: Using existing NgModules in a standalone component.

When writing a standalone component, you may want to use other components, directives, or pipes in the component's template. Some of those dependencies might not be marked as standalone, but instead declared and exported by an existing NgModule. In this case, you can import the NgModule directly into the standalone component:

@Component({
  standalone: true,
  selector: 'photo-gallery',
  // an existing module is imported directly into a standalone component
  imports: [MatButtonModule],
  template: `
    ...
    <button mat-button>Next Page</button>
  `,
})
export class PhotoGalleryComponent {
  // logic
}

You can use standalone components with existing NgModule-based libraries or dependencies in your template. Standalone components can take full advantage of the existing ecosystem of Angular libraries.


If you have StandaloneComponent and NonStandaloneComponent (which is declared in and exported from NonStandaloneModule), then you'd use the imports field on the component declaration for StandaloneComponent:

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

@Component({
  selector: 'app-standalone',
  standalone: true,
  imports: [NonStandaloneModule], // Declares and exports NonStandaloneComponent
  template: `<app-non-standalone></app-non-standalone>` // Use imported as normal
})
export class StandaloneComponent {}

Here's a StackBlitz so you can play with the idea.

Glitter answered 6/1, 2023 at 14:52 Comment(3)
For a reason, my NonStandaloneComponent does not show up. Is there anything else is should consider?Counterblast
Do you have a StackBlitz that reproduces the issue? There are many reasons it could be failing. Feel free to look at the StackBlitz linked at the bottom of my answer if you want to compare to your code and spot the difference.Glitter
For me I forgot to export NonStandaloneComponent in NonStandaloneModuleMorey

© 2022 - 2024 — McMap. All rights reserved.