简体   繁体   English

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

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

Angular 14 introduced new standalone components, which doesn't require any module to be used. Angular 14 引入了新的独立组件,不需要使用任何模块。 How can such components be used if provided in a library?如果在库中提供这些组件,如何使用这些组件? In standard, non-standalone components, we first had to import a given module.在标准的非独立组件中,我们首先必须导入给定的模块。 How Angular will recognize that component I'm importing comes from this particular package? Angular 如何识别我正在导入的组件来自这个特定的包?

To make a standalone component, you need to define the component as standalone using the standalone parameter in the decorator of the component, then you can use the imports statement in the component as well.要制作一个独立的组件,您需要在组件的装饰器中使用standalone参数将组件定义为standalone的,然后您也可以在组件中使用imports语句。 Your component would then look like this.然后,您的组件将如下所示。

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

Next you need to import the component into other components/modules.接下来,您需要将组件导入其他组件/模块。 You now can import it into your module in the import property which wasn't supported before.您现在可以在之前不支持的import属性中将其导入您的模块。 Or you can import it into another component which also wasn't supported at all, and now is.或者您可以将它导入到另一个根本不支持的组件中,现在支持。

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

If you want to use a standalone component in another component A, you need to import the standalone component in component A like below,如果要在另一个组件 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