简体   繁体   English

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

[英]How to import not standalone components to a standalone component in Angular 14+

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.我想知道如何将非独立组件导入独立组件,因为非独立组件是在 ngModule 中声明的。

There's a section of the migration documentation about this exact use case: Using existing NgModules in a standalone component .迁移文档中有一部分是关于这个确切用例的: 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 .其中一些依赖项可能不会被标记为独立的,而是由现有的NgModule声明和导出。 In this case, you can import the NgModule directly into the standalone component:在这种情况下,您可以将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 }

You can use standalone components with existing NgModule -based libraries or dependencies in your template.您可以将独立组件与模板中现有的基于NgModule的库或依赖项一起使用。 Standalone components can take full advantage of the existing ecosystem of Angular libraries.独立组件可以充分利用 Angular 库的现有生态系统。


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 :如果您有StandaloneComponentNonStandaloneComponent (在NonStandaloneModule中声明并从中导出),那么您将在StandaloneComponent的组件声明中使用imports字段:

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. 这是一个 StackBlitz ,因此您可以尝试一下这个想法。

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']
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM