Home > Enterprise >  How to import not standalone components to a standalone component in Angular 14
How to import not standalone components to a standalone component in Angular 14

Time:01-07

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.

CodePudding user response:

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.

CodePudding user response:

I'm pretty suire you use the same declarations config that you would use in a Module:

@Component({
  selector: 'app-display',
  standalone: true,
  declarations: [notAStandAloneComponent],
  imports: [CommonModule],
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
  • Related