# Angular 21 tips Angular 21 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/21/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://v22.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. > **Exceptions** Avoid using `#` if you're targeting browsers that don't natively support them, as the downleveling can impact performance and bundle size. > > You're not concerned if you use [Angular's default browserlist](https://v22.angular.dev/reference/versions#browser-support). **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` **Consider** *not* suffixing components, services and directives with their type. - ❌ `user.component.ts` for `UserComponent` class - ✅ `user-card.ts` for `UserCard` class - ❌ `user.service.ts` for `UserService` class - ✅ `user-http-client.ts` for `UserHttpClient` class - ❌ `user.directive.ts` for `UserDirective` class - ✅ `user-popover.ts` for `UserPopover` class > **Why?** Suffixes can be used to create files with the same name except for the suffix, discouraging developers to choose an appropriate and meaningful name. Several files may have a similar name even though they don't serve the same purpose at all, making it difficult to understand the differences at a glance. > > Removing suffixes encourages proper and more descriptive naming, making file names easier to read and understand. > > Note also that Angular is moving towards selectorless components in future releases. The component class name will be used in the template instead of the selector (e.g. `` instead of ``), making the suffix even less relevant. **Consider** ending the names of routed components with `page`. - ❌ `user.ts` and `User` class name - ✅ `user-page.ts` and `UserPage` class name **Consider** using `-` instead of `.` as a separator for pipes, guards, resolvers and interceptors file names. - ❌ `kebab-case.pipe.ts` - ✅ `kebab-case-pipe.ts` - ❌ `authenticated.guard.ts` - ✅ `authenticated-guard.ts` - ❌ `user.resolver.ts` - ✅ `user-resolver.ts` - ❌ `error.interceptor.ts` - ✅ `error-interceptor.ts` > **Why?** This is an official Angular recommendations and aligns with Angular's CLI generation (i.e. `ng generate pipe|guard|resolver|interceptor`). It's also consistent with the removal of the suffix mentionned above. ### 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`. > **Why?** Double equals (`==` and `!=`) performs type coercion, which can lead to unexpected results. For example, `0 == '0'` is true, but `0 === '0'` is false. > Using triple equals ensures both value and type are compared, preventing implicit and unexpected type conversion. **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() {...}` - ✅ `() => {...}` > **Why?** Arrow functions are more concise and do not bind their own `this`, avoiding common pitfalls with context binding in JavaScript. **Consider** using [pure](https://en.wikipedia.org/wiki/Pure_function) functions over impure ones. > **Why?** Pure functions are easier to test, reason about and debug. They always produce the same output for the same input and have no side effects, making them predictable and reliable. ### 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/21/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.ts` - ✅ `blog/post/blog-post.ts` - ❌ `admin/admin-dashboard/admin-dashboard-settings/admin-dashboard-settings.ts` - ✅ `admin/dashboard/settings/admin-dashboard-settings.ts` ### Project structure **Consider** splitting your codebase into 3 main folders, [`core`](https://ngtips.com/21/general/folder-structure#core-folder), [`features`](https://ngtips.com/21/general/folder-structure#features-folder) and [`shared`](https://ngtips.com/21/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 ├── auth | └── auth.ts ├── layout | ├── nav-bar | | └── nav-bar.ts | ├── page-layout | | └── page-layout.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-page.ts ├── blog | ├── feed | | └── blog-feed-page.ts | ├── post | | ├── comment | | | └── blog-post-comment.ts | | └── blog-post-page.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-page.ts ├── blog-feed-page.html ├── blog-feed-page.css ├── blog-feed-store.ts ├── blog-feed-http-client.ts └── ... ``` **Consider** creating a dedicated `.routes.ts` file for domains that contain more than one route (see [lazy loading](https://ngtips.com/21/routing#lazy-loading)). ```txt title="✅ Domain-specific route file" features ├── blog | ├── feed | | └── blog-feed-page.ts | ├── post | | └── blog-post-page.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/21/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`. **Consider** using [type inference](https://www.typescriptlang.org/docs/handbook/type-inference.html). - With primitive types: - ❌ `name: string = 'Martin'` → type is redundant - ✅ `name = 'Martin'` → type is correctly inferred as `string` - With complex types: - ❌ `status: UserStatus = this.user.status` → type is redundant - ✅ `status = this.user.status` → type is inferred from `this.user.status`'s type - ❌ `status = 'busy'` → complex type cannot be inferred from a primitive value - ✅ `status: UserStatus = 'busy'` → type must be explicitly defined - With object literals: - ❌ `user = { name: 'Martin', status: 'busy' }` → it will create a new incorrect type `{ name: string; status: string }` - ✅ `user: User = { name: 'Martin', status: 'busy' }` → type must be explicitly defined > **Tip** Type inference tips also apply to function return types. > **Why?** Type inference reduces boilerplate code by allowing TypeScript to automatically determine the type of a variable based on its value. This leads to cleaner code while still providing type safety. **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/21/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-page.ts" import { UserCard } from '../../../../shared/user-card/user-card'; ```` ```json title="✅ tsconfig.json" { ... "compilerOptions": { ... "baseUrl" : "./src", "paths": { "@shared/*": ["app/shared/*"], "@features/*": ["app/features/*"], "@core/*": ["app/core/*"] } } } ``` ```ts title="✅ user-page.ts" import { ManagerCard } from '@shared/user-card/user-card'; ```` > **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/21/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/21/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. ## Configuration Source: https://ngtips.com/21/general/configuration Proper configuration is the foundation of a maintainable and scalable Angular project. This guide covers essential configuration practices for modern Angular projects, from project setup and build optimization to environment management and code quality tools. ### General guidelines **Avoid** using NgModule. - ❌ `@NgModule` - ✅ Standalone components, directives and pipes > **Why?** NgModule is a legacy feature that is not needed in modern Angular applications and replaced by standalone components, directives and pipes. > > Standalone components are self-contained which is much easier to manage, and removing NgModules reduces boilerplate code and complexity. > **Tip** You can run the [schematic migration](https://v22.angular.dev/reference/migrations/standalone) to automatically convert your project to standalone. ### Git **Do** commit `package.json` and `package-lock.json` files. > **Why?** These files are essential for maintaining consistent dependencies across different environments and team members. Committing them ensures that everyone is using the same versions of packages, which helps prevent issues related to dependency mismatches. **Do** use `.gitignore` to exclude files that should not be committed. ```ignore title="✅ .gitignore" # Generated Angular build files /dist # Installed dependencies /node_modules # Angular CLI cache /.angular # Code coverage reports /coverage # ... ``` ### IDE **Avoid** committing personal IDE settings that aren't project-specific. - ❌ Personal themes, font sizes, or editor preferences - ✅ Shared formatting rules and essential extensions #### Visual Studio Code **Do** use Angular Language Service extension. **Do** commit recommended extensions. ```json title="✅ .vscode/extensions.json" { "recommendations": [ "angular.ng-template", ... ] } ``` #### JetBrains **Do** commit run configurations. ```ignore title="✅ .gitignore" # Ignore ".idea" folder /.idea/* # Except run configurations !/.idea/runConfigurations ``` > **Why?** Committing run configurations ensures that all team members have access to the same project run/debug settings, which can improve consistency and reduce setup time for new developers. ### Build **Do** set commonly used scripts in `package.json`. ```json title="✅ package.json" { "scripts": { "my-script": " node ./scripts/my-script.sh", ... } } ``` **Do** leverage `pre` and `post` scripts in `package.json`. ```json title="✅ package.json" { "scripts": { "prebuild": "npm run lint", "build": "ng build", "postbuild": "npm run archive" } } ``` > **Why?** `pre` and `post` scripts are executed automatically before and after the specified script, respectively. > For example, running `npm run build` will first run the `prebuild` script, then `build`, and finally `postbuild`. **Do** use the [`application` builder](https://v22.angular.dev/tools/cli/build-system-migration). ```json title="✅ angular.json" { "projects": { "your-project-name": { "architect": { "build": { "builder": "@angular/build:application", ... } } } } } ``` **Do** keep optimization enabled for production builds. ```json title="✅ angular.json" { "projects": { "your-project-name": { "architect": { "build": { "configurations": { "development": { "optimization": false, ... } }, "defaultConfiguration": "production" } } } } } ``` > **Note** Optimization is enabled by default for production builds. **Avoid** including development tools in production builds. - ❌ Source maps in production - ❌ Development dependencies in production bundles - ❌ Console logs and debug statements **Do** enable source maps in development. ```json title="✅ angular.json" { "projects": { "your-project-name": { "architect": { "build": { "configurations": { "development": { "sourceMap": true, "namedChunks": true, ... } } } } } } } ``` > **Why?** Enabling source maps in development helps with debugging by providing a way to map the minified/compiled code back to the original source code. This makes it easier to identify and fix issues during development. ### Linting & Code quality **Avoid** inconsistent code formatting across the team. - ❌ No formatting rules - ❌ Different quote styles - ❌ Inconsistent indentation **Do** use a linter. - ✅ [ESLint](https://eslint.org/): default linter for Angular projects, integrated with Angular CLI. - ✅ [Oxlint](https://oxc.rs/docs/guide/usage/linter.html): alternative to ESLint with a focus on performance and developer experience that will most likely become the next default linter. Not yet supported by Angular CLI but can be used with a custom setup, recommended if you have performance issues with ESLint. - ❌ [TSLint](https://palantir.github.io/tslint/): deprecated in favor of ESLint since 2019, not recommended for new projects. > **Tip** Run `ng lint` to automatically configure ESLint in your Angular project. **Consider** using a code formatter. - ✅ [Prettier](https://prettier.io/) - ❌ [Oxfmt](https://oxc.rs/docs/guide/usage/formatter.html): high performance code formatter that is currently in beta and not yet recommended. ### Environments & Deployments Angular provides a way to manage different environments (e.g. development or production) using environment files. These files can contain environment-specific variables that can be used throughout your application. > **Note** The environment file is included in the build process which means you need to build your application for each environment you want to deploy to. **Do** use environment files for environment-specific values. - ❌ `const API_URL = 'https://example.com'` - ✅ `import { environment } from '@environments/environment'` **Do** name environment files appropriately. - ✅ `environment.ts` for local development - ✅ `environment..ts` for others, e.g. `environment.production.ts` **Do** import only `environment.ts` file. - ❌ `import { environment } from '@environments/environment.production';` - ✅ `import { environment } from '@environments/environment';` > **Why?** This ensures that the correct environment file is used based on the file replacement configuration, preventing accidental usage of the wrong environment settings. **Do** configure file replacements in `angular.json`. ```json title="✅ angular.json" { "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ] } } } ``` #### Proxy **Do** use `proxy.conf.json` to resolve local [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) issues. ```json title="✅ proxy.conf.json" { "/api": { "target": "http://localhost:8080", "secure": false } } ``` > **Why?** Using a proxy configuration allows you to bypass CORS restrictions during development by redirecting API calls to a different server. This is particularly useful when working with APIs that are not hosted on the same domain as your Angular application. > **Note** Angular proxy is only used for the local development server (i.e. `ng serve`). It is not used nor included in production builds. > For production, you need to configure CORS on your server and/or use a reverse proxy like Nginx or Apache. ## TypeScript class Source: https://ngtips.com/21/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 `ManagerTeamPreviewMenu`: - ❌ `selector: 'app-team-preview'` - ✅ `selector: 'app-manager-team-preview-menu'` **Do** group class attributes. ```ts title="✅ user-page.ts" export class UserPage { // 1. Injected dependencies userHttpClient = inject(UserHttpClient); // 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-page.ts" export class UserPage { // Attributes userHttpClient = inject(UserHttpClient); 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://v22.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)` ### Lifecycle **Avoid** misusing or overusing component lifecycle hooks. - ❌ `ngOnInit` - ❌ `ngOnChanges` - ❌ `ngOnDestroy` - ❌ `ngDoCheck` - ❌ `ngAfterContentInit` - ❌ `ngAfterContentChecked` - ❌ `ngAfterViewInit` - ❌ `ngAfterViewChecked` - ❌ `afterEveryRender` - ❌ `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 v21 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-page.ts" export class UserPage { ngOnInit() {...} } ``` ```ts title="✅ user-page.ts" export class UserPage 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/21/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.html"
Welcome to my Website
Some important text
More details here in this description.
``` ```html title="✅ app.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: > - `