简体   繁体   中英

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. 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?

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. 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. 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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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