Skip to main content

Angular Prompt Templates

Cập nhật: 03/2026


Essential Aspects & Templates

1. Standalone Components

<role>Angular developer chuyên modern component architecture</role>

<action>
Tạo standalone component [TÊN_COMPONENT] với [CHỨC_NĂNG]
</action>

<context>
- Angular version: [VERSION]
- Component type: [PRESENTATIONAL/SMART]
- Inputs: [LIỆT_KÊ_INPUTS]
- Outputs: [LIỆT_KÊ_OUTPUTS]
- Dependencies: [SERVICES/PIPES/DIRECTIVES]
- Cần đọc existing components để học patterns
</context>

<expectation>
- @Component({ standalone: true, ... })
- TypeScript strict mode compatible
- ChangeDetectionStrategy.OnPush
- Proper Input/Output decorators
- Template: inline (simple) hoặc templateUrl (complex)
- Styles: inline hoặc styleUrls
- File: src/app/components/[name]/[name].component.ts
</expectation>

2. Services & Dependency Injection

<role>Angular architect chuyên services và DI</role>

<action>
Tạo injectable service [TÊN_SERVICE] để [MỤC_ĐÍCH]
</action>

<context>
- Service purpose: [DATA_ACCESS/BUSINESS_LOGIC/STATE_MANAGEMENT]
- Dependencies: [HttpClient, Other Services]
- Scope: [ROOT/PLATFORM/COMPONENT_LEVEL]
- Return types: [Observable/Promise/Synchronous]
- Cần đọc existing services để học patterns
</context>

<expectation>
- @Injectable({ providedIn: 'root' })
- Constructor injection với private/public access
- Methods return Observable<T> cho async operations
- Error handling với catchError operator
- TypeScript types cho all methods
- RxJS operators: map, filter, switchMap, etc.
- File: src/app/services/[name].service.ts
</expectation>

3. HTTP & API Integration

<role>Senior Angular developer chuyên HTTP communication</role>

<action>
Tạo HTTP service [TÊN_SERVICE] để interact với API [BASE_URL]
</action>

<context>
- API base URL: [URL]
- Endpoints: [GET/POST/PUT/DELETE [PATHS]]
- Authentication: [BEARER_TOKEN/API_KEY/NONE]
- Request/Response models: [INTERFACES]
- Error scenarios: [NETWORK/4XX/5XX]
- Cần đọc existing API services để học patterns
</context>

<expectation>
- Inject HttpClient: constructor(private http: HttpClient)
- Methods return Observable<T>
- Type-safe với interfaces: Observable<User[]>
- Error handling: catchError(() => throwError(...))
- Retry logic: retry(2) cho transient errors
- HTTP interceptor cho auth headers (nếu cần)
- Request/response transformation với map()
- File: src/app/services/api/[name].service.ts
</expectation>

4. RxJS & Observables

<role>Angular developer chuyên reactive programming</role>

<action>
Implement Observable stream cho [FEATURE] với operators [OPERATORS]
</action>

<context>
- Data source: [HTTP/USER_INPUT/TIMER/WEBSOCKET]
- Operators needed: [map, filter, switchMap, debounceTime, distinctUntilChanged]
- Subscription management: [ASYNC_PIPE/MANUAL/TAKE_UNTIL]
- Error handling: [CATCH_ERROR/RETRY]
- Component: [TÊN_COMPONENT]
</context>

<expectation>
- Observable pipeline với proper operators
- Type-safe: Observable<T>
- Unsubscribe strategy:
• Best: async pipe trong template
• Good: takeUntil(destroy$) pattern
• Avoid: manual subscription tracking
- Error handling với catchError
- Memory leak prevention
- ngOnDestroy với destroy$.next() nếu dùng takeUntil
</expectation>

5. Reactive Forms

<role>Senior Angular developer chuyên forms</role>

<action>
Tạo reactive form [TÊN_FORM] với validation
</action>

<context>
- Form fields: [LIỆT_KÊ_FIELDS]
- Validation rules: [REQUIRED/EMAIL/MIN_LENGTH/CUSTOM]
- Submit action: [API_CALL/LOCAL_ACTION]
- Dynamic fields: [YES/NO]
- Cần đọc existing forms để học validation patterns
</context>

<expectation>
- Import ReactiveFormsModule
- FormBuilder injection: private fb = inject(FormBuilder)
- FormGroup with typed controls
- Validators: Validators.required, Validators.email, custom validators
- Template: formControlName bindings
- Error display: *ngIf="form.get('field')?.errors?.['required']"
- Submit: (ngSubmit)="onSubmit()" với form.valid check
- Disable button while invalid: [disabled]="form.invalid || isSubmitting"
- File: [name].component.ts + [name].component.html
</expectation>

6. Routing & Navigation

<role>Frontend architect chuyên routing</role>

<action>
Setup Angular Router cho [SỐ_ROUTES] routes với lazy loading và guards
</action>

<context>
- Routes: [LIỆT_KÊ_ROUTES]
- Protected routes: [AUTHENTICATION_REQUIRED]
- Layout structure: [NESTED/FLAT]
- Route guards: [AUTH_GUARD/ROLE_GUARD]
- Lazy loading: [YES/NO]
</context>

<expectation>
- Routes array trong app.routes.ts
- Lazy loading: loadComponent: () => import('...').then(m => m.Component)
- Route guards: canActivate: [AuthGuard]
- Route parameters: path: 'user/:id'
- Child routes với outlet: <router-outlet>
- 404 route: path: '**', component: NotFoundComponent
- Navigation: Router inject + router.navigate(['/path'])
- File: src/app/app.routes.ts
</expectation>

7. State Management

<role>Angular architect chuyên state management</role>

<action>
Implement state management cho [FEATURE] với [NGRX/SERVICE_PATTERN]
</action>

<context>
- State complexity: [SIMPLE/COMPLEX]
- Approach: [NGRX_STORE/RXJS_SERVICE]
- State properties: [LIỆT_KÊ_STATE]
- Actions: [LIỆT_KÊ_ACTIONS]
- Side effects: [API_CALLS/TIMERS]
</context>

<expectation>
Simple state (Service pattern):
- Service với BehaviorSubject<T>
- Public Observable: state$ = this._state.asObservable()
- Update methods: setState(newState)
- Immutable updates với spread operator

Complex state (NgRx):
- Actions: createAction('[Source] Event')
- Reducer: createReducer() với on() handlers
- Selectors: createFeatureSelector(), createSelector()
- Effects: createEffect() cho async operations
- Store registration trong app config
- File structure: +state/actions, reducers, selectors, effects
</expectation>

8. Testing

<role>QA Engineer chuyên Angular testing</role>

<action>
Viết unit tests cho [COMPONENT/SERVICE] covering all behaviors
</action>

<context>
- Test subject: [COMPONENT/SERVICE/PIPE/DIRECTIVE]
- Dependencies: [SERVICES/HTTP/ROUTER]
- Interactions: [USER_EVENTS/API_CALLS]
- Test framework: Jasmine/Karma hoặc Jest
- Coverage target: >= 80%
</context>

<expectation>
- TestBed.configureTestingModule() setup
- Mock dependencies: jasmine.createSpyObj()
- Component tests:
• fixture.detectChanges() after changes
• debugElement.query(By.css('selector'))
• User events: trigger + detectChanges
- Service tests:
• HttpClientTestingModule cho HTTP services
• expect + flush mock responses
- Async: fakeAsync, tick, flush
- File: [name].spec.ts
</expectation>

9. Signals (Angular 16+)

<role>Angular developer chuyên modern reactivity</role>

<action>
Refactor component [TÊN] từ RxJS sang Signals
</action>

<context>
- Component: [PATH]
- Current: BehaviorSubject + async pipe
- State properties: [LIỆT_KÊ_STATE]
- Computed values: [DERIVED_STATE]
- Side effects: [EFFECTS]
</context>

<expectation>
- Import: signal, computed, effect từ @angular/core
- Replace BehaviorSubject: mySignal = signal(initialValue)
- Computed values: myComputed = computed(() => mySignal() * 2)
- Side effects: effect(() => { console.log(mySignal()) })
- Template: {{ mySignal() }} (no async pipe needed)
- Update: mySignal.set(newValue) hoặc mySignal.update(val => val + 1)
- Performance: fine-grained reactivity
</expectation>

Best Practices Checklist

  • ✅ Angular version specified (19+)
  • ✅ Standalone components (không NgModules)
  • ✅ TypeScript strict mode
  • ✅ OnPush change detection
  • ✅ inject() function thay vì constructor injection
  • ✅ Signals cho state (Angular 16+)
  • ✅ Async pipe hoặc takeUntil cho subscriptions
  • ✅ Proper error handling
  • ✅ Testing coverage >= 80%