Motivation

With Angular 14 the new concept of standalone components has found its way into the Angular eco-system. With the help of this new approach the creation of Angular components is now easier than ever before.

Standalone components do not need to be included in any of Angular’s NgModule files. Hence, they prevent modules from bloating out especially when building bigger applications.

 

Creating such components is fairly simple: In the @Component decorator the boolean property standalone has to be enabled. That’s it in general.
Furthermore, standalone components can also be imported in other standalone components.

 

Code-Example

Let’s assume we want to  import the existing standalone component UserImageComponent in the UserProfileComponent:

@Component({
  standalone: true,
  selector: 'user-profile',
  imports: [UserImageComponent]
})
export class UserProfileComponent {
  // component logic
}

This does not only work for standalone components, but also for non-standalone components, directives or pipes. So importing a non-standalone component in a standalone component works by exporting it in the surrounding NgModule and importing the module in the component afterwards.

 

For instance, if a developer wants to import a CalendarComponent which is declard in the CalendarModule , this can be achieved as follows:

 

@Component({
  standalone: true,
  selector: 'user-profile',
  imports: [CalendarModule],
  template: `
    ...
    
  `
})
export class UserProfileComponent {
  // component logic
}

The two code examples are merely demonstration material without any business logic. Nevertheless, they show well how easy it is to combine standalone components with legacy components prior v14.

 

Of course, there is much more to learn, but for the sake of brevity only the most important concepts are shown in this article. If you want to learn more about standalone components, especially how they are used with routing, visit the official Angular documentationen here.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments