如何从 Angular 14 中的库导入独立组件?

Kar*_*rol 21 angular angular14

Angular 14 引入了新的独立组件,不需要使用任何模块。如果库中提供了这些组件,如何使用?在标准的非独立组件中,我们首先必须导入给定的模块。Angular 如何识别我导入的组件来自这个特定的包?

Get*_*awn 23

要制作一个独立的组件,您需要在组件的装饰器中将组件定义为standalone使用参数,然后您也可以在组件中使用该语句。standaloneimports

使用独立标志生成:

ng generate component example-component --standalone
Run Code Online (Sandbox Code Playgroud)

相反,如果您希望整个项目是独立的,则可以将标志添加standalonenew命令中,然后不必在命令standalone上指定generate

ng new my-application --standalone

ng g c example-component
Run Code Online (Sandbox Code Playgroud)

您的组件将如下所示:

@Component({
  standalone: true,
  imports: [CommonModule],
  selector: 'example-component',
  template: `./example.component.html`,
})
export class ExampleComponent {}
Run Code Online (Sandbox Code Playgroud)

接下来,您需要将该组件导入到其他组件/模块中。您现在可以将其导入到import以前不支持的属性中的模块中。或者您可以将其导入到另一个根本不支持的组件中,但现在是了。

注意:导入组件的组件也需要该standalone属性。

// Importing using a Module
@NgModule({
  imports: [ExampleComponent]
})
export class MyModule {}

// Importing using a component
// This component also needs the standalone property
@Component({
  standalone: true,
  imports: [ExampleComponent],
  selector: 'some-component',
  template: `./component.html`,
})
export class OtherExampleComponent {}
Run Code Online (Sandbox Code Playgroud)

  • 我忘记导入组件还需要独立属性 (2认同)

小智 7

如果你想在另一个组件A中使用独立组件,你需要在组件A中导入独立组件,如下所示,

@Component({
  standalone: true,
  imports: [StandaloneComponent],
  selector: 'demo-component',
  template: `./demo.component.html`,
})
Run Code Online (Sandbox Code Playgroud)