DEV Community

Dan Bui
Dan Bui

Posted on

Standalone component in Angular

Standalone components were officially released with Angular 15. After one year of using it, converting to standalone components, in this post, I will share my experiences of using it

SCAM

Before touching the standalone component, let’s start with SCAM. What is SCAM?
SCAM stands for Single Component As Module. It is the golden rule for creating a shared component ui, looks like this:

shared-button-ui/
├── shared-button-ui.component.ts
├── shared-button-ui.component.html
├── shared-button-ui.component.scss
└── shared-button-ui.module.ts
Enter fullscreen mode Exit fullscreen mode

Inside shared-button-ui.module.ts

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [SharedUiButtonComponent],
  exports: [SharedUiButtonComponent],
})
export class SharedUiButtonModule {}
Enter fullscreen mode Exit fullscreen mode
  • Declare SharedUiButtonComponent inside the declarations array
  • Then re-export them by defining inside the exports array
  • Anywhere that intends to use SharedUiButtonComponent, must import SharedUiButtonModule

Standalone Component

Since version 14, Angular has introduced standalone components, pipes, and directives. It looks like this:

@Component({
  selector: 'app-button-ui',
  imports: [
    MatProgressSpinner,
    OtherNgModules
  ],
  templateUrl: './shared-button-ui.component.html',
  standalone: true,
  styleUrl: './shared-button-ui.component.scss'
})
export class ShareButtonUiComponent {}
Enter fullscreen mode Exit fullscreen mode

Pay your attention to the Components’ metadata; there are two new properties:

  • imports
  • standalone

Compared to before, it is similar to mixing @NgModule with @Component together. Is it right? The answer is right!
With the “alone” style, now a component, pipe, or directive is an @NgModule itself. It means:

  • Standalone don’t rely on ngModule anymore
  • Standalone can import their dependencies
  • Standalone can be imported by other components or modules directly

So far, we mentioned SCAM best way for creating a shared component. And now, Standalone is a perfect replacement. Compare to SCAM:

  • Reduce boilerplate code, without creating ngModule
  • Avoid redundant imports, such as putting inside the SharedModule together

Conclusion

In the recent update from Angular’s team, they focus on streamlining DX as well as the Development process, a standalone component is one of them! It is a great time to convert our regular components into standalone components. We must not convert all at once; we can adopt incrementally

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.