如何在 Angular 14+ 中将非独立组件导入到独立组件

Luc*_*ade 8 angular angular14 angular15

我想知道如何将非独立组件导入到独立组件中,因为非独立组件是在 ngModule 中声明的。

D M*_*D M 7

迁移文档中有一部分关于这个确切的用例:在独立组件中使用现有的 NgModules

编写独立组件时,您可能希望在组件模板中使用其他组件、指令或管道。其中一些依赖项可能不会标记为独立的,而是由现有的NgModule. 在这种情况下,您可以NgModule直接将其导入到独立组件中:

@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
}
Run Code Online (Sandbox Code Playgroud)

您可以将独立组件与NgModule模板中现有的基于库或依赖项一起使用。独立组件可以充分利用现有的 Angular 库生态系统。


如果您有StandaloneComponentand NonStandaloneComponent(在 中声明并从 中导出NonStandaloneModule),那么您可以使用imports组件声明中的字段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 {}
Run Code Online (Sandbox Code Playgroud)

这是一个 StackBlitz,您可以尝试一下这个想法。