šAngular Quick Bite: Standalone componentes [English]
Angular Standalone components
Independent components, also known as āstandalone components,ā are a type of component used to create reusable components that are not part of any NgModule and can be used with other standalone components or module-based components.
How are standalone components, directives, and pipes created?
To create a standalone component, a new component must be generated using the Angular command line interface.
A standalone component, pipe, or directive can be created using the standalone flag:
ng g p search --standalone
ng g d text --standalone
ng g c login --standalone
Starting in Angular 14, we can turn a component into a standalone by adding āstandalone: trueā to the class and directly importing its dependencies without the need to declare it in an NgModule:
@Component({
standalone: true,
selector: 'photo-gallery',
imports: [ImageGridComponent],
template: `
... <image-grid [images]="imageList"></image-grid>
`,
})
export class PhotoGalleryComponent {
// component logic
}
The important thing is to ensure that it does not depend on any other component, that is, its functionality and design are independent and not based on the logic of other components. This makes the component easy to use and maintain, as it can be used anywhere in the application.
What can we do with standalone components?
- Use existing NgModules in a standalone component
- Use standalone components in module-based applications
- Bootstrap an application using a standalone component
- Routing and lazy loading of standalone components
Conclusion
Standalone components are a powerful tool in an Angular developerās arsenal. With the ability to create standalone components, code reuse, scalability, and application performance can be improved. Finally, the main goal of standalone components is to optimize the experience of creating components, pipes, and directives by reducing the need for NgModules.