Angular Labs
COOKIES
general / Prefer Standalone Components

Prefer Standalone Components

Use standalone components instead of NgModules when possible for better modularity and tree-shaking

Official Angular Style Guide @angular-eslint/prefer-standalone

Examples

✅ Good - Standalone Component

import { Component } from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
@Component({
selector: "app-user-profile",
standalone: true,
imports: [CommonModule, FormsModule],
template: `
<div class="user-profile">
<h2>{{ user.name }}</h2>
<input [(ngModel)]="user.email" placeholder="Email" />
<button (click)="save()">Save</button>
</div>
`,
})
export class UserProfileComponent {
user = { name: "John Doe", email: "john@example.com" };
save() {
// Save logic here
}
}

✅ Good - Standalone Component with Dependencies

import { Component, inject } from "@angular/core";
import { CommonModule } from "@angular/common";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
@Component({
selector: "app-data-display",
standalone: true,
imports: [CommonModule],
template: `
<div *ngIf="data$ | async as data">
<h3>{{ data.title }}</h3>
<p>{{ data.description }}</p>
</div>
`,
})
export class DataDisplayComponent {
private http = inject(HttpClient);
data$: Observable<any> = this.http.get("/api/data");
}

❌ Bad - Traditional NgModule Approach

user-profile.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-user-profile",
template: `
<div class="user-profile">
<h2>{{ user.name }}</h2>
<input [(ngModel)]="user.email" placeholder="Email" />
<button (click)="save()">Save</button>
</div>
`,
})
export class UserProfileComponent {
user = { name: "John Doe", email: "john@example.com" };
save() {
// Save logic here
}
}
// user-profile.module.ts
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { UserProfileComponent } from "./user-profile.component";
@NgModule({
declarations: [UserProfileComponent],
imports: [CommonModule, FormsModule],
exports: [UserProfileComponent],
})
export class UserProfileModule {}

✅ Good - Bootstrapping Standalone App

main.ts
import { bootstrapApplication } from "@angular/platform-browser";
import { AppComponent } from "./app/app.component";
import { provideRouter } from "@angular/router";
import { routes } from "./app/app.routes";
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
// other providers
],
});