Reusable Components & Architecture in Angular - Textnotes

Reusable Components & Architecture in Angular


Building reusable components and following a scalable architecture is essential for maintaining large Angular applications efficiently.

1. Smart vs Dumb Components

Smart Components (Container Components)

  1. Handle business logic and data fetching
  2. Interact with services and state
  3. Pass data to dumb components via @Input and receive events via @Output

@Component({
selector: 'app-user-container',
template: `<app-user-list [users]="users" (delete)="deleteUser($event)"></app-user-list>`
})
export class UserContainerComponent {
users = [];

constructor(private userService: UserService) {}

ngOnInit() {
this.users = this.userService.getUsers();
}

deleteUser(userId: number) {
this.userService.deleteUser(userId);
}
}

Dumb Components (Presentational Components)

  1. Focus on UI rendering only
  2. Receive data via @Input and emit events via @Output
  3. No direct service or state dependency

@Component({
selector: 'app-user-list',
template: `
<ul>
<li *ngFor="let user of users">
{{ user.name }}
<button (click)="delete.emit(user.id)">Delete</button>
</li>
</ul>
`
})
export class UserListComponent {
@Input() users: any[] = [];
@Output() delete = new EventEmitter<number>();
}

2. Shared Components

Components that are reused across multiple modules:

  1. Buttons, modals, tables, input fields
  2. Place in a shared module and import in other modules:

@NgModule({
declarations: [ButtonComponent, ModalComponent],
exports: [ButtonComponent, ModalComponent]
})
export class SharedModule {}

3. Feature Folders

Organize code by features rather than by type:


/users
/components
user-list.component.ts
user-form.component.ts
/services
user.service.ts
/models
user.model.ts
user.module.ts
  1. Makes it easy to maintain, scale, and lazy-load modules

4. Clean & Scalable Architecture

Best Practices:

  1. Smart/Dumb separation – keeps UI and logic separate
  2. Feature modules – organize by domain (users, products, orders)
  3. Shared module – reusable components, directives, pipes
  4. Core module – singleton services and app-wide providers
  5. State management – RxJS or NgRx for predictable state
  6. Lazy loading – improve performance for large apps
  7. Follow Angular style guide for consistent folder structure

Summary

  1. Separate smart (container) and dumb (presentational) components.
  2. Use shared components for reuse across modules.
  3. Organize code into feature folders for scalability.
  4. Maintain a clean and modular architecture for maintainability and performance.