DEV Community

Cover image for How to Prompt an LLM to Write Angular Code: Straight from the Experts
Dhanush D
Dhanush D

Posted on

How to Prompt an LLM to Write Angular Code: Straight from the Experts

Writing Angular code with an AI assistant is like pair programming with someone who knows everything, but only if you ask the right questions.

This guide will walk you through the best way to prompt LLMs for Angular apps and components, using expert approved TypeScript and Angular practices.

TypeScript and Angular Best Practices

So here’s a checklist of best practices one should expect the LLM to follow. Use these to inform the prompt and verify the output.


TypeScript Best Practices

  • Use strict type checking

    The prompt should always assume the project uses strict: true in tsconfig.json.

  • Prefer type inference when obvious

    Let TypeScript do the work where possible no need to clutter code with redundant types.

  • Avoid any; use unknown instead

    any kills type safety. If you don’t know the type yet, ask for unknown + type guards.


Angular Best Practices

Components

  • Always use standalone components (No need of standalone: true; it’s implicit).
  • Use signals and computed() for state management.
  • Keep components small and single-responsibility.
  • Use input() and output() functions instead of decorators @input and @output.
  • Set changeDetection: ChangeDetectionStrategy.OnPush.
  • Prefer inline templates for small components.
  • Avoid ngClass and ngStyle use [class] and [style] bindings instead.
  • Prefer Reactive Forms over template driven ones.

Services

  • Design services with single responsibility.
  • Use providedIn: 'root' for singleton services.
  • Use the inject() function, not constructor injection.

State & Templates

  • Use signals for local state.
  • Use computed() for derived values.
  • Keep state pure and predictable.
  • In templates, avoid complex logic.
  • Use native control flow (@if, @for, @switch) over structural directives like *ngIf, *ngFor, *ngSwitch.
  • Use the async pipe for observables.

Assets & Routing

  • Use NgOptimizedImage for all static images.
  • Use lazy loading for all feature routes.

When Reviewing LLM Generated Code

LLMs can hallucinate or use outdated patterns. When reviewing the code, always check for:

  • ✅ Use of signals over RxJS unless necessary
  • computed() for derived state
  • ✅ Proper use of inject() in services
  • ✅ Inline templates for simple components
  • ✅ Avoidance of *ngIf, *ngFor in favor of @if, @for
  • ✅ No ngClass or ngStyle

Happy prompting

Top comments (0)