We use cookies to enhance your experience on the site
CodeWorlds

Standalone Components vs NgModules

Angular 17+ prefers Standalone Components - a simpler approach without modules.

Comparison of Approaches

Old Way (NgModule-based)

1// samurai.component.ts
2@Component({
3  selector: 'app-samurai',
4  templateUrl: './samurai.component.html'
5})
6export class SamuraiComponent { }
7
8// samurai.module.ts
9@NgModule({
10  declarations: [SamuraiComponent],
11  imports: [CommonModule, SharedModule],
12  exports: [SamuraiComponent]
13})
14export class SamuraiModule { }

New Way (Standalone)

1// samurai.component.ts - everything in one file!
2@Component({
3  selector: 'app-samurai',
4  standalone: true,
5  imports: [CommonModule, CardComponent, ButtonComponent],
6  templateUrl: './samurai.component.html'
7})
8export class SamuraiComponent { }
9
10// Usage - direct import
11@Component({
12  standalone: true,
13  imports: [SamuraiComponent]
14})
15export class AppComponent { }

Lazy Loading with Standalone

1// app.routes.ts
2export const routes: Routes = [
3  {
4    path: 'samurai',
5    loadComponent: () => import('./samurai/samurai.component')
6      .then(c => c.SamuraiComponent)
7  },
8  {
9    path: 'dojo',
10    loadChildren: () => import('./dojo/dojo.routes')
11      .then(r => r.DOJO_ROUTES)
12  }
13];

When to Use Which?

| Scenario | Recommendation | |----------|----------------| | New project (Angular 17+) | Standalone Components | | Legacy project | Stay with NgModules | | Angular library | Standalone (easier to use) | | Large enterprise project | You can mix both approaches |

Go to CodeWorlds