# Angular 19 tips Angular 19 best practices from ngtips.com. **Do** tips must always be followed. **Consider** tips should generally be followed, deviate only with a good reason. **Avoid** tips should almost never be done. ## Code style Source: https://ngtips.com/19/general/code-style This page covers best practices and common mistakes when writing TypeScript code, focusing on those with the highest impact. It includes naming conventions, code clarity, consistency and more. The following guidelines are a complement to the [Angular official coding style guide](https://v19.angular.dev/style-guide) that we recommend to read first. ### General guidelines **Do** maintain consistency. **Consider** clarity over short code. **Do** ensure explicitness. **Avoid** redundancy. ### Naming **Do** use PascalCase for enum, class, type and interface names. - ❌ `userProfile` - ❌ `user_profile` - ✅ `UserProfile` **Avoid** including type indicator in interface names. - ❌ `IUser` - ❌ `UserInterface` - ❌ `UserInt` - ✅ `User` **Avoid** including type indicator in enum names. - ❌ `EUserStatus` - ❌ `UserStatusEnum` - ✅ `UserStatus` **Do** use camelCase for variable and method names. - ❌ `my_var` - ✅ `myVar` - ❌ `MyMethod()` - ✅ `myMethod()` **Avoid** using abbreviation in names, prefer whole words. - ❌ `usrCnt` - ✅ `userCount` **Do** prefix private properties with `#`. - ❌ `_myVar` - ❌ `private myVar` - ✅ `#myVar` > **Why?** `private` is a TypeScript keyword enforced at compile time and removed after compilation, it can be bypassed at runtime, whereas `#` is a JavaScript feature that ensures the property is private at runtime. **Do** use plural form in names for iterables (array, set, ...). - ❌ `userList = getUserArray()` - ✅ `users = getUsers()` **Avoid** ambiguity. - ❌ `id: number` (unclear if referring to a user or company ID) - ✅ `userId: number` - ✅ `companyId: number` **Do** structure variable names to reflect ownership, ending with the specific value. - ❌ `idUser: number` - ✅ `userId: number` - ❌ `nameOfManagerInCompanyDepartment: string` - ✅ `companyDepartmentManagerName: string` **Consider** starting function and method names with a verb. - ❌ `user()` - ✅ `getUser()` **Do** use common verbs appropriately in function and method names. - ✅ `get`: return a value, no side effect. - ✅ `set`: assign a new value to a property, no returned value. - ✅ `is`/`has`: return a boolean, no side effect. - ✅ `create`: instantiate a new instance of an object. - ✅ `delete`: delete an object. - ✅ `add`: insert one or multiple elements in a collection. - ✅ `remove`: take one or multiple elements out of a collection. - ✅ `to`: convert one type to another and return it, no side effect. - ✅ `toggle`: switch between binary state. > **Why?** Following a clear, strict and consitent pattern with function names improves readability and predictability. > Developers will quickly understand a function's purpose without the need to read it's content, avoiding misinterpretation. **Do** name Maps by combining a description of the key and the value, separated by `To`. - ❌ `usersMap: Map` (unclear what the key and value are) - ✅ `userIdToManager: Map` - ✅ `companyIdToUsers: Map` ### Code **Avoid** using `var`, use `const` by default and `let` if necessary. - ❌ `var a = 1` - ✅ `const a = 1` - ✅ `let a = 1` **Do** use triple equals over doubles. - ❌ `a == b` - ✅ `a === b` - ❌ `a != b` - ✅ `a !== b` - exception: comparing to `null` or `undefined`. **Do** use single quotes for string. - ❌ `"some text"` - ✅ `'some text'` **Do** use template literals for string interpolation. - ❌ `'I am ' + age + 'years old.'` - ✅ `` `I am ${age} years old.` `` **Do** use arrow function over anonymous function. - ❌ `function() {...}` - ✅ `() => {...}` **Consider** using [pure](https://en.wikipedia.org/wiki/Pure_function) functions over impure ones. ### Comments **Do** ensure comments explain _why_, not _how_. **Do** include a reference to the task in `TODO` and `FIXME` comments. - ❌ `// TODO improve performance` - ✅ `// TODO #2831: improve performance` (GitHub issue or Jira ticket) ## Folder structure Source: https://ngtips.com/19/general/folder-structure Folder structure refers to *how* files and directories are organized within a project. A well-designed methodology helps developers navigate the codebase efficiently and, above all, keeps the project understandable and maintanable as it grows. It provides a clear separation of concerns, making it easier to locate, update, and manage different parts of the application. ### General guidelines **Consider** grouping files by domain (business feature) rather than technical type (components, services, ...). **Consider** structuring the file tree as close as possible to the routing and navigation in the application. **Do** rename folders to avoid redundancy in path. - ❌ `blog/blog-post/blog-post.component.ts` - ✅ `blog/post/blog-post.component.ts` - ❌ `admin/admin-dashboard/admin-dashboard-settings/admin-dashboard-settings.component.ts` - ✅ `admin/dashboard/settings/admin-dashboard-settings.component.ts` ### Project structure **Consider** splitting your codebase into 3 main folders, [`core`](https://ngtips.com/19/general/folder-structure#core-folder), [`features`](https://ngtips.com/19/general/folder-structure#features-folder) and [`shared`](https://ngtips.com/19/general/folder-structure#shared-folder). ```txt title="✅ Project structure" ├── public ├── src │ ├── app │ │ ├── core │ │ ├── features │ │ ├── shared │ │ └── ... │ ├── environments │ ├── index.html │ ├── styles.scss │ └── ... ├── angular.json ├── package.json └── ... ``` #### core folder **Do** include non-business and global features in `core` folder. - ✅ Layout components - ✅ Authentication service - ✅ Interceptors - ... > **Note** `core` folder usually contains files that are instantiated once or used globally. ```txt title="✅ core folder" core ├── authentication | └── authentication.service.ts ├── layout | ├── nav-bar | | └── nav-bar.component.ts | ├── page-layout | | └── page-layout.component.ts | └── ... ├── interceptors | ├── error-handler.interceptor.ts | └── ... └── ... ``` **Avoid** importing files from `features` folder into the `core` folder. #### features folder **Do** include business features grouped by domain in `features` folder. ```txt title="✅ features folder" features ├── dashboard | └── dashboard.component.ts ├── blog | ├── feed | | └── blog-feed.component.ts | ├── post | | └── blog-post.component.ts | └── blog.routes.ts └── ... ``` > **Tip** Nested folders under `features` can be as deep as needed to represent the domain structure of your application. **Do** colocate files related to the same feature in the same folder. ```txt title="✅ Colocated files" feed ├── blog-feed.component.ts ├── blog-feed.component.html ├── blog-feed.component.css ├── blog-feed.store.ts ├── blog-feed.service.ts └── ... ``` **Consider** creating a dedicated `.routes.ts` file for domains that contain more than one route (see [lazy loading](https://ngtips.com/19/routing#lazy-loading)). ```txt title="✅ Domain-specific route file" features ├── blog | ├── feed | | └── blog-feed.component.ts | ├── post | | └── blog-post.component.ts // highlight-start | └── blog.routes.ts // highlight-end └── ... ``` #### shared folder **Do** include reusable components, services, directives and other files in `shared` folder. > **Note** For some files under the `shared` folder, such as generic utilities or highly reusable code, grouping by domain doesn't make sense. Instead, you can organize them by technical type (like components, services or directives). ```txt title="✅ shared folder" shared ├── components | ├── form | | ├── color-picker | | ├── search-bar | | ├── input-file | | └── ... | ├── confirm-dialog | └── ... ├── directives ├── models ├── pipes ├── services └── ... ``` **Avoid** importing files from `core` or `features` folders into the `shared` folder. ## Typing Source: https://ngtips.com/19/general/typing Typing is a fundamental aspect of Angular application that ensures your code is robust, maintainable, and less prone to runtime errors. This guide provides best practices for leveraging TypeScript's type system effectively, helping you write cleaner and safer code. By following these tips, you'll improve the readability and scalability of your projects while catching potential issues early during development. ### General guidelines **Do** type everything. > **Why?** Typing improves readability, scalability and maintanability. Type inconsistencies will be detected at compile time rather than at runtime, before shipping to production. **Avoid** using `any`. ```ts title="❌ any" // This code compiles but will throw an error at runtime: // "Uncaught TypeError: Cannot read properties of undefined (reading 'name')" const user: any = { name: 'Martin' }; console.log(user.manager.name); ``` ```ts title="✅ Proper typing" // This code fails to compile, it'll show you a friendly error: // "Property 'manager' does not exist on type 'User'." interface User { name: string; } const user: User = { name: 'Martin' }; console.log(user.manager.name); ``` > **Why?** Using `any` completely bypass type checking, as if there were no type at all. > **Tip** If the type doesn't matter, use `unknown` instead of `any`. **Do** define an `interface` for structural types, not a `class`. ```ts title="❌ class" class User { constructor(id: number, name: string) { this.id = id; this.name = name; } } ``` ```ts title="✅ interface" interface User { id: number; name: string; } ``` **Do** use specific values instead of generic types like `string` or `number`. - ❌ `status: string` - ✅ `status: 'active' | 'inactive' | 'pending'` - ❌ `priority: number` - ✅ `priority: 1 | 2 | 3` > **Why?** Using union types ensures that only specific, predefined values, are allowed, reducing the risk of invalid inputs and improving code clarity. **Do** use tuple types for fixed-length arrays. - ❌ `parents: string[]` - ✅ `parents: [string, string]` for 2 elements - ✅ `siblings: [string, ...string[]]` for at least 1 element > **Why?** Using tuple types ensures that the array has a fixed length and specific types for each element, improving type safety and reducing potential errors. ### Null safety JavaScript has two special values: `null` and `undefined`. When strict null checks are enabled (see [TypeScript configuration](https://ngtips.com/19/general/typing#typescript-configuration)), `null` and `undefined` are not assignable to any type unless explicitly specified. > **Tip** You should use this feature to prevent "Null Pointer Exceptions" at runtime. TypeScript will warn you if you try to access a property of an object that might be `null` or `undefined`. On the other hand, if the object is guaranteed to be non-null, you can safely access its properties without any additional checks. > **Note** No preferences for `null` or `undefined` in TypeScript, but be consistent in your codebase. **Avoid** unnecessary `null` and `undefined` types. - ❌ `status: Status | null = 'pending'` - ❌ `status: Status | undefined = 'pending'` - ❌ `status?: Status = 'pending'` - ✅ `status: Status = 'pending'` > **Why?** Excessive use of optional types can lead to unnecessary code to handle `null` or `undefined` cases that will never occur. Or, it may also encourage developers to bypass the optional typing (using `name!`) which lead to runtime errors if a `null` case does occur. **Do** use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). - ✅ `user?.manager?.name` **Do** use [nullish coalescing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing). - ✅ `name ?? 'Default name'` **Do** use [non-null assertion operator](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-). - ✅ `user!.name` > **Warning** Use the non-null assertion operator with caution. It tells TypeScript to ignore the possibility of `null` or `undefined`, but it can still lead to runtime errors if you're not careful and the value is actually `null` or `undefined`. > > Use it only when you're absolutely sure that the value will never be `null` or `undefined` in your specific case. ### TypeScript configuration **Do** use the following compiler options in your [TypeScript configuration](https://www.typescriptlang.org/tsconfig/) file: ```json title="✅ tsconfig.json" { ... "compilerOptions": { ... "strict": true, "allowUnreachableCode": false, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noUncheckedIndexedAccess": true } } ``` **Do** use import aliases. ```ts title="❌ user.component.ts" import { ManagerComponent } from '../../../../shared/manager/manager.component'; ```` ```json title="✅ tsconfig.json" { ... "compilerOptions": { ... "baseUrl" : "./src", "paths": { "@shared/*": ["app/shared/*"], "@features/*": ["app/features/*"], "@core/*": ["app/core/*"] } } } ``` ```ts title="✅ user.component.ts" import { ManagerComponent } from '@shared/manager/manager.component'; ```` > **Why?** Using import aliases improves code readability and reduces the number of import paths to be modified when moving files. ## Third-party libraries Source: https://ngtips.com/19/general/third-party-libraries In the next pages, we will mention some third-party libraries that can help you build robust Angular applications efficiently. Each are production-ready and battle-tested libraries, with their pros and cons, that are widely used by the community. > **Note** If a library is not mentionned, it doesn't mean it's bad or not recommended. It just means that we haven't had the chance to evaluate it yet. You can suggest a library on GitHub, see [how to contribute](https://ngtips.com/19/contributing). ### General guidelines **Do** use as few dependencies as possible. > **Why?** Each dependency you add to your project increases the complexity, the size of your application and the maintenance cost. Keeping your dependencies up to date will be more and more time consuming. It's important to carefully evaluate each dependency and only include those that are absolutely necessary and worth the trade-off. **Do** choose a library carefully and knowingly. > **Why?** Libraries can rapidly evolve and change over time. They can be deprecated, abandoned, refactored, or replaced by better alternatives. > Having an outdated or poorly maintained library in your project can lead to security vulnerabilities, bugs, and compatibility issues that prevent you from upgrading to the latest version of Angular or other libraries. > > Replacing a library can be a painful and time-consuming process, especially if it is deeply integrated into your application. It can require significant refactoring and testing to ensure that everything works correctly with the new library. > **Tip** Beware of trends and hype cycle, when building a long-term large application, aim for libraries that are: > - Functional: offers the features you need > - Mature and stable: tried and tested by others > - Actively maintained: regular improvements, bug fixes, security patches, ... > - Long-term supported (LTS): guaranteed support for a certain period of time > - Compatible: with other tools in your application > - Popular: for useful community resources and to attract/keep qualified developers. A library with a large user base is more likely to be maintained in the long run. > > Run tests or proof of concept to compare solutions and ensure that the chosen one is right for you. **Avoid** mixing multiple libraries that serve the same purpose. > **Why?** Using multiple libraries that offer similar functionality can lead to confusion and potential conflicts, making your code harder to maintain and understand. It also increases the bundle size of your application, which can impact performance and loading times. ## TypeScript class Source: https://ngtips.com/19/component/typescript-class This page provides best practices and recommendations for writing TypeScript classes in Angular components. ### General guidelines **Do** use seperate files for class, template and style. > **Exception** You can use a single file for components with no style and extremely short template (1 to 3 lines). **Do** use standalone components. - ❌ `@Component({ standalone: false, ... })` - ✅ `@Component({ ... })` (default value is `true`) **Do** use a selector prefix. - ❌ `selector: 'user-card'` - ✅ `selector: 'app-user-card'` > **Tip** `app-` is the default Angular selector prefix, and in most cases it is fine. If needed, you can change it, but keep it short. > > In multi-project workspace, it could be a good thing to have a different prefix for each project. **Do** use the same name for component class name and the selector, but with a prefix and in kebab-case. - Given the component class `ManagerTeamPreviewMenuComponent`: - ❌ `selector: 'app-team-preview'` - ✅ `selector: 'app-manager-team-preview-menu'` **Do** group class attributes. ```ts title="✅ user.component.ts" export class UserComponent { // 1. Injected dependencies userService = inject(UserService); // 2. Constants UserStatus = UserStatus; // 3. Inputs user = input.required(); // 4. Outputs delete = output(); // 5. Internal component states profileForm = new FormGroup(...); userManager = computed(...); } ``` **Do** declare attributes first, then methods. ```ts title="✅ user.component.ts" export class UserComponent { // Attributes userService = inject(UserService); user = input.required(); form = new FormGroup(...); // Methods constructor() {...} createSomething() {...} submit() {...} } ``` ### Inputs & outputs **Do** use `input()` signal and `output()` function instead of `@Input()` and `@Ouput()` decorators. > **Tip** You can run [schematic migrations](https://v19.angular.dev/reference/migrations) to automatically transform decorators to signals. **Do** type inputs and outputs. - ❌ `input()` - ❌ `input()` - ✅ `input()` - ❌ `output()` - ✅ `output()` (void by default) - ✅ `output()` **Do** use `input.required()` signal for required inputs. - ❌ `mandatoryField = input()` - ✅ `mandatoryField = input.required()` **Do** use `model()` signal for two-way binding. - ❌ `selected = input(false)` and `selectedChange = output()` - ✅ `selected = model(false)` ### Change detection **Consider** using `ChangeDetectionStrategy.OnPush` for every components. - ❌ unspecified change detection strategy - ❌ `changeDetection: ChangeDetectionStrategy.Default` - ✅ `changeDetection: ChangeDetectionStrategy.OnPush` > **Why?** The main reason is sustainability. Angular is heading towards better reactivity with signals and Zoneless application, and using `OnPush` now will make migration to future major releases easier. > > In addition, `OnPush` strategy improves performances by reducing the number of change detection cycles, which is particularly interesting for large projects. > **Tip** You can set the default change detection strategy to `OnPush` in your `angular.json` file for components generated with Angular CLI. More info about change detection in [Reactivity](https://ngtips.com/19/reactivity). ### Lifecycle **Avoid** misusing or overusing component lifecycle hooks. - ❌ `ngOnInit` - ❌ `ngOnChanges` - ❌ `ngOnDestroy` - ❌ `ngDoCheck` - ❌ `ngAfterContentInit` - ❌ `ngAfterContentChecked` - ❌ `ngAfterViewInit` - ❌ `ngAfterViewChecked` - ❌ `afterRender` - ❌ `afterNextRender` > **Why?** These methods are often used to do things you should avoid, like manipulating the DOM, and where reactive patterns are a better fit. Some alternatives: > - `computed()` and `effect()` signals > - `viewChild()` and `viewChildren()` signals > - `takeUntilDestroyed()` rxjs operator > - ... > > Use signals and observables first and lifecycle hooks as a last resort. > > You can initialize your component inside the `constructor` instead of the `ngOnInit` method. > **Exceptions** Because Angular v19 is not completely signal-based yet, you will need to rely on lifecycle hooks in some cases, for example: > - Initializing a form > - Accessing route data > - ... **Do** implement the lifecycle interface if its lifecycle method is defined. ```ts title="❌ user.component.ts" export class UserComponent { ngOnInit() {...} } ``` ```ts title="✅ user.component.ts" export class UserComponent implements OnInit { ngOnInit() {...} } ``` > **Why?** Angular will call your component's lifecycle methods even if it does not explicitly implement the interface, but make sure you implement it for type safety. ### DOM interaction **Avoid** direct DOM access or manipulation. - ❌ `document.getElementById('my-button')` - ❌ `document.createElement('div')` - ❌ `window.innerWidth` > **Why?** Direct DOM access breaks Angular's abstraction layer and makes testing and maintenance harder. Direct DOM accesses are likely to break in future changes, as they are not type-checked. Prefer Angular's reactive and declarative approach instead, some examples: > - Conditional rendering > - `viewChild()`, `viewChildren()`, `contentChild` and `contentChildren()` queries > - Templating with `` or `` > - Angular Material `MediaMatcher` > - ... ## Template Source: https://ngtips.com/19/component/template This page outlines best practices for Angular component's templates, focusing on organization, readability, accessibilty and performance. By following these guidelines, you'll ensure your templates are maintainable, readable, and aligned with Angular's recommended patterns. ### General guidelines **Do** use as few tags as possible. **Consider** using meaningful semantic HTML elements instead of non-semantic ones. ```html title="❌ app.component.html"
Welcome to my Website
Some important text
More details here in this description.
``` ```html title="✅ app.component.html"

Welcome to my Website

Some important text

More details here in this description.

...
``` > **Tip** Use `
` or `` as last resort if no more suitable element exists, a few examples: > - `