繁体   English   中英

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

[英]How to import standalone components from a lib in Angular 14?

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

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

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

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

// 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 ExampleComponent {}

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

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

暂无
暂无

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

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