From c757dff37f4551edf9100889aff6e3ea8714721d Mon Sep 17 00:00:00 2001 From: Suguru Inatomi Date: Thu, 20 Nov 2025 07:40:13 +0900 Subject: [PATCH 01/55] feat: update origin to 21.0.0 --- origin | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/origin b/origin index 31f2030320..63a95c7b9e 160000 --- a/origin +++ b/origin @@ -1 +1 @@ -Subproject commit 31f2030320c868e46db98786959cf421e6f758ca +Subproject commit 63a95c7b9e6cc2dc5296331507ec028ca92ee2c4 From 74ba3111516ebe9347bce6aa426341ff60fe8510 Mon Sep 17 00:00:00 2001 From: Suguru Inatomi Date: Thu, 20 Nov 2025 07:40:40 +0900 Subject: [PATCH 02/55] fix: migrate new files --- adev-ja/src/content/ai/ai-tutor.md | 150 +++ adev-ja/src/content/events/v21.md | 27 + .../src/content/guide/aria/autocomplete.md | 190 ++++ adev-ja/src/content/guide/aria/menubar.md | 198 ++++ adev-ja/src/content/guide/aria/multiselect.md | 201 ++++ adev-ja/src/content/guide/aria/select.md | 193 ++++ .../guide/di/creating-and-using-services.md | 105 ++ .../guide/di/defining-dependency-providers.md | 923 ++++++++++++++++++ .../content/guide/forms/signals/comparison.md | 163 ++++ .../src/content/guide/forms/signals/models.md | 536 ++++++++++ .../content/guide/forms/signals/overview.md | 59 ++ adev-ja/src/content/guide/testing/karma.md | 199 ++++ .../guide/testing/migrating-to-vitest.md | 229 +++++ .../introduction/essentials/signal-forms.md | 254 +++++ .../reference/extended-diagnostics/NG8021.md | 179 ++++ .../migrations/common-to-standalone.md | 61 ++ .../router-testing-module-migration.md | 103 ++ .../playground/4-signal-forms/config.json | 5 + 18 files changed, 3775 insertions(+) create mode 100644 adev-ja/src/content/ai/ai-tutor.md create mode 100644 adev-ja/src/content/events/v21.md create mode 100644 adev-ja/src/content/guide/aria/autocomplete.md create mode 100644 adev-ja/src/content/guide/aria/menubar.md create mode 100644 adev-ja/src/content/guide/aria/multiselect.md create mode 100644 adev-ja/src/content/guide/aria/select.md create mode 100644 adev-ja/src/content/guide/di/creating-and-using-services.md create mode 100644 adev-ja/src/content/guide/di/defining-dependency-providers.md create mode 100644 adev-ja/src/content/guide/forms/signals/comparison.md create mode 100644 adev-ja/src/content/guide/forms/signals/models.md create mode 100644 adev-ja/src/content/guide/forms/signals/overview.md create mode 100644 adev-ja/src/content/guide/testing/karma.md create mode 100644 adev-ja/src/content/guide/testing/migrating-to-vitest.md create mode 100644 adev-ja/src/content/introduction/essentials/signal-forms.md create mode 100644 adev-ja/src/content/reference/extended-diagnostics/NG8021.md create mode 100644 adev-ja/src/content/reference/migrations/common-to-standalone.md create mode 100644 adev-ja/src/content/reference/migrations/router-testing-module-migration.md create mode 100644 adev-ja/src/content/tutorials/playground/4-signal-forms/config.json diff --git a/adev-ja/src/content/ai/ai-tutor.md b/adev-ja/src/content/ai/ai-tutor.md new file mode 100644 index 0000000000..fd3b01aed9 --- /dev/null +++ b/adev-ja/src/content/ai/ai-tutor.md @@ -0,0 +1,150 @@ +# Angular AI Tutor + +The Angular AI Tutor is designed to interactively guide you step-by-step through building a complete, modern Angular application from the ground up. You'll learn the latest patterns and best practices by building a real, tangible project: a **"Smart Recipe Box"** for creating and managing recipes. + +Our goal is to foster critical thinking and help you retain what you learn. Instead of just giving you code, the tutor will explain concepts, show you examples, and then give you project-specific exercises to solve on your own. + +## Get Started + +You can access the AI tutor via the [Angular MCP server](ai/mcp). + +1. [Install](ai/mcp#get-started) the Angular MCP server +2. Create a new Angular project `ng new ` +3. Navigate to your new project (`cd `) in an AI-powered editor or tool, like the [Gemini CLI](https://geminicli.com/) +4. Enter a prompt like `launch the Angular AI tutor` + ![A screenshot demonstrating how to launch the Angular AI Tutor in the Gemini CLI.](assets/images/launch-ai-tutor.png 'Launch the Angular AI Tutor') + +## Using the AI Tutor + +Each module begins with a brief concept explanation. +![A screenshot of the Angular AI Tutor presenting a brief concept explanation.](assets/images/ai-tutor-preview-1.png 'Angular AI Tutor explanation') +If applicable, the tutor will present a code example to demonstrate the concept. +![A screenshot of the Angular AI Tutor showing a code example.](assets/images/ai-tutor-preview-2.png 'Angular AI Tutor code example') +The tutor will also provide an open-ended exercise to test your understanding. +![A screenshot of the Angular AI Tutor providing an exercise.](assets/images/ai-tutor-preview-3.png 'Angular AI Tutor exercise') +Finally, the tutor will check your work before moving onto the next module. +![A screenshot of the Angular AI Tutor checking the user's work.](assets/images/ai-tutor-preview-4.png 'Angular AI Tutor check') + +## How It Works: The Learning Cycle + +For each new topic, you'll follow a learning loop that emphasizes critical thinking to help you better retain what you learn. + +1. **Learn the Concept:** The tutor will briefly explain a core Angular feature and show you a generic code example to illustrate it. +2. **Apply Your Knowledge:** You'll immediately get a hands-on exercise. The tutor presents these exercises at a high level with objectives and expected outcomes, encouraging you to think through the solution yourself. +3. **Get Feedback & Support:** When you're ready, let the tutor know. It will **automatically read your project files** to verify your solution is correct. If you get stuck, you are in complete control. You can ask for a **"hint"** for more guidance, or get step-by-step instructions by typing **"detailed guide"** or **"step-by-step instructions."** + +Once you've succeeded, the tutor will move directly to the next topic. You can also ask the tutor for more information on a topic or ask any related Angular questions at any time. + +--- + +## **Features & Commands** + +You are in control of your learning experience. Use these features at any time: + +### **Leave and Come Back** + +Feel free to take a break. Your progress is tied to your project's code. When you return for a new session, the tutor will automatically analyze your files to determine exactly where you left off, allowing you to seamlessly pick up right where you were. + +**Pro Tip:** We highly recommend using Git to save your progress. After completing a module, it's a great idea to commit your changes (e.g., `git commit -m "Complete Phase 1, Module 8"`). This acts as a personal checkpoint you can always return to. + +### **Adjust Your Experience Level** + +You can set your experience level to **Beginner (1-3)**, **Intermediate (4-7)**, or **Experienced (8-10)**. You can change this setting at any time during your session, and the tutor will immediately adapt its teaching style to match. + +**Example Prompts:** + +- "Set my experience level to beginner." +- "Change my rating to 8." + +### **See the Full Learning Plan** + +Want to see the big picture or check how far you've come? Just ask for the table of contents. + +**Example Prompts:** + +- "Where are we?" +- "Show the table of contents." +- "Show the plan." + +The tutor will display the full learning plan and mark your current location. + +### **A Note on Styling** + +The tutor will apply basic styling to your application to keep things looking clean. You are highly encouraged to apply your own styling to make the app your own. + +### **Skip the Current Module** + +If you'd rather move on to the next topic in the learning path, you can ask the tutor to skip the current exercise. + +**Example Prompts:** + +- "Skip this section." +- "Auto-complete this step for me." + +The tutor will ask for confirmation and then present you with the complete code solution for the current module and attempt to automatically apply any required updates to ensure you can continue smoothly with the next module. + +### **Jump to Any Topic** + +If you want to learn about a specific topic out of order (e.g., jump from the basics to forms), you can. The tutor will provide the necessary code to update your project to the correct starting point for the selected module and attempt to automatically apply any required updates. + +**Example Prompts:** + +- "Take me to the forms lesson." +- "I want to learn about Route Guards now." +- "Jump to the section on Services." + +--- + +## **Troubleshooting** + +If the tutor doesn't respond correctly or you suspect an issue with your application, here are a few things to try: + +1. **Type "proceed":** This can often nudge the tutor to continue to the next step in the event it gets stuck. +2. **Correct the Tutor:** If the tutor is mistaken about your progress (e.g., it says you're on Module 3 but you've completed Module 8), just tell it. For example: _"I'm actually on Module 8."_ The tutor will re-evaluate your code and adjust. +3. **Verify Your UI:** If you want to confirm what your application's user interface should look like, just ask the tutor. For example: _"What should I see in my UI?"_ +4. **Reload the Browser Window:** A refresh can solve many issues related to your application. +5. **Hard Restart the Browser:** Errors are sometimes only surfaced in the browser's developer console. A hard restart can help clear underlying issues related to the application. +6. **Start a New Chat:** You can always start a new chat to remove the existing history and begin fresh. The tutor will read your files to find the latest step you were on. + +## **Your Learning Journey: The Phased Path** + +You will build your application over a four-phase journey. You can follow this path from start to finish to create a complete, fully-functional Angular application. Each module builds logically upon the last, taking you from the basics to advanced, real-world features. + +**A Note on Automated Setup:** Some modules require a setup step, like creating interfaces or mock data. In these cases, the tutor will present you with the code and file instructions. You will be responsible for creating and modifying these files as instructed before the exercise begins. + +### **Phase 1: Angular Fundamentals** + +- **Module 1:** Getting Started +- **Module 2:** Dynamic Text with Interpolation +- **Module 3:** Event Listeners (`(click)`) + +### **Phase 2: State and Signals** + +- **Module 4:** State Management with Writable Signals (Part 1: `set`) +- **Module 5:** State Management with Writable Signals (Part 2: `update`) +- **Module 6:** Computed Signals + +### **Phase 3: Component Architecture** + +- **Module 7:** Template Binding (Properties & Attributes) +- **Module 8:** Creating & Nesting Components +- **Module 9:** Component Inputs with Signals +- **Module 10:** Styling Components +- **Module 11:** List Rendering with `@for` +- **Module 12:** Conditional Rendering with `@if` + +### **Phase 4: Advanced Features & Architecture** + +- **Module 13:** Two-Way Binding +- **Module 14:** Services & Dependency Injection (DI) +- **Module 15:** Basic Routing +- **Module 16:** Introduction to Forms +- **Module 17:** Intro to Angular Material + +--- + +## **A Note on AI & Feedback** + +This tutor is powered by a Large Language Model (LLM). While we've worked hard to make it an expert, AIs can make mistakes. If you encounter an explanation or code example that seems incorrect, please let us know. You can correct the tutor, and it will use your feedback to adjust its response. + +For any technical bugs or feature requests, please [submit an issue](https://github.com/angular/angular-cli/issues). diff --git a/adev-ja/src/content/events/v21.md b/adev-ja/src/content/events/v21.md new file mode 100644 index 0000000000..856de18a0f --- /dev/null +++ b/adev-ja/src/content/events/v21.md @@ -0,0 +1,27 @@ +![A retro 8-bit, pixel art style graphic announcing the upcoming release of Angular v21. The large, gradient 'v21' text dominates the frame. Next to it, in smaller text, are the words 'The Adventure Begins' and the release date '11-20-2025' inside a pink pixelated box. The Angular logo is in the bottom right corner.](assets/images/angular-v21-hero.jpg 'Angular v21 Hero Image') + +# Angular v21: The Adventure Begins + +## Save the Date November 20, 2025 + + + + + + +
+ +Join the Angular team this November for a brand new release adventure. With modern AI tooling, performance updates and more, Angular v21 delivers fantastic new features to improve your developer experience. Whether you’re creating AI-powered apps or scalable enterprise applications, there has never been a better time to build with Angular. + +🔥 What's coming in v21 + +- New Angular MCP Server tools to improve AI-powered workflows and code generation +- Your first look at Signal Forms, our new streamlined, signal-based approach to forms in Angular +- Exciting new details about the Angular ARIA package + +That’s just a taste of what’s coming in our upcoming major release event. You won't want to miss it. + + + + + diff --git a/adev-ja/src/content/guide/aria/autocomplete.md b/adev-ja/src/content/guide/aria/autocomplete.md new file mode 100644 index 0000000000..f1fd46946e --- /dev/null +++ b/adev-ja/src/content/guide/aria/autocomplete.md @@ -0,0 +1,190 @@ + + + +## Overview + +An accessible input field that filters and suggests options as users type, helping them find and select values from a list. + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Usage + +Autocomplete works best when users need to select from a large set of options where typing is faster than scrolling. Consider using autocomplete when: + +- **The option list is long** (more than 20 items) - Typing narrows down choices faster than scrolling through a dropdown +- **Users know what they're looking for** - They can type part of the expected value (like a state name, product, or username) +- **Options follow predictable patterns** - Users can guess partial matches (like country codes, email domains, or categories) +- **Speed matters** - Forms benefit from quick selection without extensive navigation + +Avoid autocomplete when: + +- The list has fewer than 10 options - A regular dropdown or radio group provides better visibility +- Users need to browse options - If discovery is important, show all options upfront +- Options are unfamiliar - Users can't type what they don't know exists in the list + +## Features + +Angular's autocomplete provides a fully accessible combobox implementation with: + +- **Keyboard Navigation** - Navigate options with arrow keys, select with Enter, close with Escape +- **Screen Reader Support** - Built-in ARIA attributes for assistive technologies +- **Three Filter Modes** - Choose between auto-select, manual selection, or highlighting behavior +- **Signal-Based Reactivity** - Reactive state management using Angular signals +- **Popover API Integration** - Leverages the native HTML Popover API for optimal positioning +- **Bidirectional Text Support** - Automatically handles right-to-left (RTL) languages + +## Examples + +### Auto-select mode + +Users typing partial text expect immediate confirmation that their input matches an available option. Auto-select mode updates the input value to match the first filtered option as users type, reducing the number of keystrokes needed and providing instant feedback that their search is on the right track. + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Manual selection mode + +Manual selection mode keeps the typed text unchanged while users navigate the suggestion list, preventing confusion from automatic updates. The input only changes when users explicitly confirm their choice with Enter or a click. + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Highlight mode + +Highlight mode allows the user to navigate options with arrow keys without changing the input value as they browse until they explicitly select a new option with Enter or click. + + + + + + + + + + + + + + + + + + + + + + + + + + + +## APIs + +### Combobox Directive + +The `ngCombobox` directive provides the container for autocomplete functionality. + +#### Inputs + +| Property | Type | Default | Description | +| ------------ | ---------------------------------------------- | ---------- | ------------------------------------------------- | +| `filterMode` | `'auto-select'` \| `'manual'` \| `'highlight'` | `'manual'` | Controls selection behavior | +| `disabled` | `boolean` | `false` | Disables the combobox | +| `firstMatch` | `string` | - | The value of the first matching item in the popup | + +#### Outputs + +| Property | Type | Description | +| ---------- | ----------------- | ----------------------------------------------------- | +| `expanded` | `Signal` | Signal indicating whether the popup is currently open | + +### ComboboxInput Directive + +The `ngComboboxInput` directive connects an input element to the combobox. + +#### Model + +| Property | Type | Description | +| -------- | -------- | ------------------------------------------------------------ | +| `value` | `string` | Two-way bindable string value of the input using `[(value)]` | + +### ComboboxPopupContainer Directive + +The `ngComboboxPopupContainer` directive wraps the popup content and manages its display. + +Must be used with `` inside a popover element. + +### Related components + +Autocomplete uses [Listbox](/api/aria/listbox/Listbox) and [Option](/api/aria/listbox/Option) directives to render the suggestion list. See the [Listbox documentation](/guide/aria/listbox) for additional customization options. diff --git a/adev-ja/src/content/guide/aria/menubar.md b/adev-ja/src/content/guide/aria/menubar.md new file mode 100644 index 0000000000..780d7af8b7 --- /dev/null +++ b/adev-ja/src/content/guide/aria/menubar.md @@ -0,0 +1,198 @@ + + + + + + + + +## Overview + +The manubar is a horizontal navigation bar that provides persistent access to application menus. Menubars organize commands into logical categories like File, Edit, and View, helping users discover and execute application features through keyboard or mouse interaction. + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Usage + +Menubars work well for organizing application commands into persistent, discoverable navigation. + +**Use menubars when:** + +- Building application command bars (such as File, Edit, View, Insert, Format) +- Creating persistent navigation that stays visible across the interface +- Organizing commands into logical top-level categories +- Need horizontal menu navigation with keyboard support +- Building desktop-style application interfaces + +**Avoid menubars when:** + +- Building dropdown menus for individual actions (use [Menu with trigger](guide/aria/menu) instead) +- Creating context menus (use [Menu](guide/aria/menu) guide pattern) +- Simple standalone action lists (use [Menu](guide/aria/menu) instead) +- Mobile interfaces where horizontal space is limited +- Navigation belongs in a sidebar or header navigation pattern + +## Features + +- **Horizontal navigation** - Left/Right arrow keys move between top-level categories +- **Persistent visibility** - Always visible, not modal or dismissable +- **Hover-to-open** - Submenus open on hover after first keyboard or click interaction +- **Nested submenus** - Support multiple levels of menu depth +- **Keyboard navigation** - Arrow keys, Enter/Space, Escape, and typeahead search +- **Disabled states** - Disable entire menubar or individual items +- **RTL support** - Automatic right-to-left language navigation + +## Examples + +### Basic menubar + +A menubar provides persistent access to application commands organized into top-level categories. Users navigate between categories with Left/Right arrows and open menus with Enter or Down arrow. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Press Right arrow to move between File, Edit, and View. Press Enter or Down arrow to open a menu and navigate submenu items with Up/Down arrows. + +### Disabled menubar items + +Disable specific menu items or the entire menubar to prevent interaction. Control whether disabled items can receive keyboard focus with the `softDisabled` input. + + + + + + + + + + + + + + + + + + + + + + + + + + + +When `[softDisabled]="true"` on the menubar, disabled items can receive focus but cannot be activated. When `[softDisabled]="false"`, disabled items are skipped during keyboard navigation. + +### RTL support + +Menubars automatically adapt to right-to-left (RTL) languages. Arrow key navigation reverses direction, and submenus position on the left side. + + + + + + + + + + + + + + + + + + + + + + + + + + + +The `dir="rtl"` attribute enables RTL mode. Left arrow moves right, Right arrow moves left, maintaining natural navigation for RTL language users. + +## APIs + +The menubar pattern uses directives from Angular's Aria library. See the [Menu guide](guide/aria/menu) for complete API documentation. + +### MenuBar + +The horizontal container for top-level menu items. + +#### Inputs + +| Property | Type | Default | Description | +| -------------- | --------- | ------- | ------------------------------------------------------------- | +| `disabled` | `boolean` | `false` | Disables the entire menubar | +| `wrap` | `boolean` | `true` | Whether keyboard navigation wraps from last to first item | +| `softDisabled` | `boolean` | `true` | When `true`, disabled items are focusable but not interactive | + +See the [Menu API documentation](guide/aria/menu#apis) for complete details on all available inputs and signals. + +### MenuItem + +Individual items within the menubar. Same API as Menu - see [MenuItem](guide/aria/menu#menuitem). + +**Menubar-specific behavior:** + +- Left/Right arrows navigate between menubar items (vs Up/Down in vertical menus) +- First keyboard interaction or click enables hover-to-open for submenus +- Enter or Down arrow opens the submenu and focuses the first item +- `aria-haspopup="menu"` indicates items with submenus + +### MenuTrigger + +Not typically used in menubars - MenuItem handles trigger behavior directly when it has an associated submenu. See [MenuTrigger](guide/aria/menu#menutrigger) for standalone menu trigger patterns. diff --git a/adev-ja/src/content/guide/aria/multiselect.md b/adev-ja/src/content/guide/aria/multiselect.md new file mode 100644 index 0000000000..dc27f4a676 --- /dev/null +++ b/adev-ja/src/content/guide/aria/multiselect.md @@ -0,0 +1,201 @@ + + + +## Overview + +A pattern that combines readonly combobox with multi-enabled listbox to create multiple-selection dropdowns with keyboard navigation and screen reader support. + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Usage + +The multiselect pattern works best when users need to choose multiple related items from a familiar set of options. + +Consider using this pattern when: + +- **Users need multiple selections** - Tags, categories, filters, or labels where multiple choices apply +- **The option list is fixed** (fewer than 20 items) - Users can scan options without search +- **Filtering content** - Multiple criteria can be active simultaneously +- **Assigning attributes** - Labels, permissions, or features where multiple values make sense +- **Related choices** - Options that logically work together (such as selecting multiple team members) + +Avoid this pattern when: + +- **Only single selection is needed** - Use the [Select pattern](guide/aria/select) for simpler single-choice dropdowns +- **The list has more than 20 items with search needed** - Use the [Autocomplete pattern](guide/aria/autocomplete) with multiselect capability +- **Most or all options will be selected** - A checklist pattern provides better visibility +- **Choices are independent binary options** - Individual checkboxes communicate the choices more clearly + +## Features + +The multiselect pattern combines [Combobox](guide/aria/combobox) and [Listbox](guide/aria/listbox) directives to provide a fully accessible dropdown with: + +- **Keyboard Navigation** - Navigate options with arrow keys, toggle with Space, close with Escape +- **Screen Reader Support** - Built-in ARIA attributes including aria-multiselectable +- **Selection Count Display** - Shows compact "Item + 2 more" pattern for multiple selections +- **Signal-Based Reactivity** - Reactive state management using Angular signals +- **Smart Positioning** - CDK Overlay handles viewport edges and scrolling +- **Persistent Selection** - Selected options remain visible with checkmarks after selection + +## Examples + +### Basic multiselect + +Users need to select multiple items from a list of options. A readonly combobox paired with a multi-enabled listbox provides familiar multiselect functionality with full accessibility support. + + + + + + + + + + + + + + + + + + + + + + + + + + + +The `multi` attribute on `ngListbox` enables multiple selection. Press Space to toggle options, and the popup remains open for additional selections. The display shows the first selected item plus a count of remaining selections. + +### Multiselect with custom display + +Options often need visual indicators like icons or colors to help users identify choices. Custom templates within options allow rich formatting while the display value shows a compact summary. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Each option displays an icon alongside its label. The display value updates to show the first selection's icon and text, followed by a count of additional selections. Selected options show a checkmark for clear visual feedback. + +### Controlled selection + +Forms sometimes need to limit the number of selections or validate user choices. Programmatic control over selection enables these constraints while maintaining accessibility. + + + + + + + + + + + + + + + + + + + + + + + + + + + +This example limits selections to three items. When the limit is reached, unselected options become disabled, preventing additional selections. A message informs users about the constraint. + +## APIs + +The multiselect pattern uses the following directives from Angular's Aria library. See the full API documentation in the linked guides. + +### Combobox Directives + +The multiselect pattern uses `ngCombobox` with the `readonly` attribute to prevent text input while preserving keyboard navigation. + +#### Inputs + +| Property | Type | Default | Description | +| ---------- | --------- | ------- | ----------------------------------------- | +| `readonly` | `boolean` | `false` | Set to `true` to create dropdown behavior | +| `disabled` | `boolean` | `false` | Disables the entire multiselect | + +See the [Combobox API documentation](guide/aria/combobox#apis) for complete details on all available inputs and signals. + +### Listbox Directives + +The multiselect pattern uses `ngListbox` with the `multi` attribute for multiple selection and `ngOption` for each selectable item. + +#### Inputs + +| Property | Type | Default | Description | +| -------- | --------- | ------- | ------------------------------------------ | +| `multi` | `boolean` | `false` | Set to `true` to enable multiple selection | + +#### Model + +| Property | Type | Description | +| -------- | ------- | ----------------------------------------- | +| `values` | `any[]` | Two-way bindable array of selected values | + +When `multi` is true, users can select multiple options using Space to toggle selection. The popup remains open after selection, allowing additional choices. + +See the [Listbox API documentation](guide/aria/listbox#apis) for complete details on listbox configuration, selection modes, and option properties. + +### Positioning + +The multiselect pattern integrates with [CDK Overlay](api/cdk/overlay/CdkConnectedOverlay) for smart positioning. Use `cdkConnectedOverlay` to handle viewport edges and scrolling automatically. diff --git a/adev-ja/src/content/guide/aria/select.md b/adev-ja/src/content/guide/aria/select.md new file mode 100644 index 0000000000..fa7f431c4c --- /dev/null +++ b/adev-ja/src/content/guide/aria/select.md @@ -0,0 +1,193 @@ + + + +## Overview + +A pattern that combines readonly combobox with listbox to create single-selection dropdowns with keyboard navigation and screen reader support. + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Usage + +The select pattern works best when users need to choose a single value from a familiar set of options. + +Consider using this pattern when: + +- **The option list is fixed** (fewer than 20 items) - Users can scan and choose without filtering +- **Options are familiar** - Users recognize the choices without needing to search +- **Forms need standard fields** - Country, state, category, or status selection +- **Settings and configuration** - Dropdown menus for preferences or options +- **Clear option labels** - Each choice has a distinct, scannable name + +Avoid this pattern when: + +- **The list has more than 20 items** - Use the [Autocomplete pattern](guide/aria/autocomplete) for better filtering +- **Users need to search options** - [Autocomplete](guide/aria/autocomplete) provides text input and filtering +- **Multiple selection is needed** - Use the [Multiselect pattern](guide/aria/multiselect) instead +- **Very few options exist (2-3)** - Radio buttons provide better visibility of all choices + +## Features + +The select pattern combines [Combobox](guide/aria/combobox) and [Listbox](guide/aria/listbox) directives to provide a fully accessible dropdown with: + +- **Keyboard Navigation** - Navigate options with arrow keys, select with Enter, close with Escape +- **Screen Reader Support** - Built-in ARIA attributes for assistive technologies +- **Custom Display** - Show selected values with icons, formatting, or rich content +- **Signal-Based Reactivity** - Reactive state management using Angular signals +- **Smart Positioning** - CDK Overlay handles viewport edges and scrolling +- **Bidirectional Text Support** - Automatically handles right-to-left (RTL) languages + +## Examples + +### Basic select + +Users need a standard dropdown to choose from a list of values. A readonly combobox paired with a listbox provides the familiar select experience with full accessibility support. + + + + + + + + + + + + + + + + + + + + + + + + + + + +The `readonly` attribute on `ngCombobox` prevents text input while preserving keyboard navigation. Users interact with the dropdown using arrow keys and Enter, just like a native select element. + +### Select with custom display + +Options often need visual indicators like icons or badges to help users identify choices quickly. Custom templates within options allow rich formatting while maintaining accessibility. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Each option displays an icon alongside the label. The selected value updates to show the chosen option's icon and text, providing clear visual feedback. + +### Disabled select + +Selects can be disabled to prevent user interaction when certain form conditions aren't met. The disabled state provides visual feedback and prevents keyboard interaction. + + + + + + + + + + + + + + + + + + + + + + + + + + + +When disabled, the select shows a disabled visual state and blocks all user interaction. Screen readers announce the disabled state to assistive technology users. + +## APIs + +The select pattern uses the following directives from Angular's Aria library. See the full API documentation in the linked guides. + +### Combobox Directives + +The select pattern uses `ngCombobox` with the `readonly` attribute to prevent text input while preserving keyboard navigation. + +#### Inputs + +| Property | Type | Default | Description | +| ---------- | --------- | ------- | ----------------------------------------- | +| `readonly` | `boolean` | `false` | Set to `true` to create dropdown behavior | +| `disabled` | `boolean` | `false` | Disables the entire select | + +See the [Combobox API documentation](guide/aria/combobox#apis) for complete details on all available inputs and signals. + +### Listbox Directives + +The select pattern uses `ngListbox` for the dropdown list and `ngOption` for each selectable item. + +#### Model + +| Property | Type | Description | +| -------- | ------- | ---------------------------------------------------------------------------- | +| `values` | `any[]` | Two-way bindable array of selected values (contains single value for select) | + +See the [Listbox API documentation](guide/aria/listbox#apis) for complete details on listbox configuration, selection modes, and option properties. + +### Positioning + +The select pattern integrates with [CDK Overlay](api/cdk/overlay/CdkConnectedOverlay) for smart positioning. Use `cdkConnectedOverlay` to handle viewport edges and scrolling automatically. diff --git a/adev-ja/src/content/guide/di/creating-and-using-services.md b/adev-ja/src/content/guide/di/creating-and-using-services.md new file mode 100644 index 0000000000..f8df5139a9 --- /dev/null +++ b/adev-ja/src/content/guide/di/creating-and-using-services.md @@ -0,0 +1,105 @@ +# Creating and using services + +Services are reusable pieces of code that can be shared across your Angular application. They typically handle data fetching, business logic, or other functionality that multiple components need to access. + +## Creating a service + +You can create a service with the [Angular CLI](tools/cli) with the following command: + +```bash +ng generate service CUSTOM_NAME +``` + +This creates a dedicated `CUSTOM_NAME.ts` file in your `src` directory. + +You can also manually create a service by adding the `@Injectable()` decorator to a TypeScript class. This tells Angular that the service can be injected as a dependency. + +Here is an example of a service that allows users to add and request data: + +```ts +// 📄 src/app/basic-data-store.ts +import { Injectable } from '@angular/core'; + +@Injectable({ providedIn: 'root' }) +export class BasicDataStore { + private data: string[] = [] + + addData(item: string): void { + this.data.push(item) + } + + getData(): string[] { + return [...this.data] + } +} +``` + +## How services become available + +When you use `@Injectable({ providedIn: 'root' })` in your service, Angular: + +- **Creates a single instance** (singleton) for your entire application +- **Makes it available everywhere** without any additional configuration +- **Enables tree-shaking** so the service is only included in your JavaScript bundle if it's actually used + +This is the recommended approach for most services. + +## Injecting a service + +Once you've created a service with `providedIn: 'root'`, you can inject it anywhere in your application using the `inject()` function from `@angular/core`. + +### Injecting into a component + +```angular-ts +import { Component, inject } from '@angular/core'; +import { BasicDataStore } from './basic-data-store'; + +@Component({ + selector: 'app-example', + template: ` +
+

{{ dataStore.getData() }}

+ +
+ ` +}) +export class ExampleComponent { + dataStore = inject(BasicDataStore); +} +``` + +### Injecting into another service + +```ts +import { inject, Injectable } from '@angular/core'; +import { AdvancedDataStore } from './advanced-data-store'; + +@Injectable({ + providedIn: 'root', +}) +export class BasicDataStore { + private advancedDataStore = inject(AdvancedDataStore); + private data: string[] = []; + + addData(item: string): void { + this.data.push(item); + } + + getData(): string[] { + return [...this.data, ...this.advancedDataStore.getData()]; + } +} +``` + +## Next steps + +While `providedIn: 'root'` covers most use cases, Angular offers additional ways to provide services for specialized scenarios: + +- **Component-specific instances** - When components need their own isolated service instances +- **Manual configuration** - For services that require runtime configuration +- **Factory providers** - For dynamic service creation based on runtime conditions +- **Value providers** - For providing configuration objects or constants + +You can learn more about these advanced patterns in the next guide: [defining dependency providers](/guide/di/defining-dependency-providers). diff --git a/adev-ja/src/content/guide/di/defining-dependency-providers.md b/adev-ja/src/content/guide/di/defining-dependency-providers.md new file mode 100644 index 0000000000..3702715d59 --- /dev/null +++ b/adev-ja/src/content/guide/di/defining-dependency-providers.md @@ -0,0 +1,923 @@ +# Defining dependency providers + +Angular provides two ways to make services available for injection: + +1. **Automatic provision** - Using `providedIn` in the `@Injectable` decorator or by providing a factory in the `InjectionToken` configuration +2. **Manual provision** - Using the `providers` array in components, directives, routes, or application config + +In the [previous guide](/guide/di/creating-and-using-services), you learned how to create services using `providedIn: 'root'`, which handles most common use cases. This guide explores additional patterns for both automatic and manual provider configuration. + +## Automatic provision for non-class dependencies + +While the `@Injectable` decorator with `providedIn: 'root'` works great for services (classes), you might need to provide other types of values globally - like configuration objects, functions, or primitive values. Angular provides `InjectionToken` for this purpose. + +### What is an InjectionToken? + +An `InjectionToken` is an object that Angular's dependency injection system uses to uniquely identify values for injection. Think of it as a special key that lets you store and retrieve any type of value in Angular's DI system: + +```ts +import { InjectionToken } from '@angular/core'; + +// Create a token for a string value +export const API_URL = new InjectionToken('api.url'); + +// Create a token for a function +export const LOGGER = new InjectionToken<(msg: string) => void>('logger.function'); + +// Create a token for a complex type +export interface Config { + apiUrl: string; + timeout: number; +} +export const CONFIG_TOKEN = new InjectionToken('app.config'); +``` + +NOTE: The string parameter (e.g., `'api.url'`) is a description purely for debugging — Angular identifies tokens by their object reference, not this string. + +### InjectionToken with `providedIn: 'root'` + +An `InjectionToken` that has a `factory` results in `providedIn: 'root'` by default (but can be overidden via the `providedIn` prop). + +```ts +// 📁 /app/config.token.ts +import { InjectionToken } from '@angular/core'; + +export interface AppConfig { + apiUrl: string; + version: string; + features: Record; +} + +// Globally available configuration using providedIn +export const APP_CONFIG = new InjectionToken('app.config', { + providedIn: 'root', + factory: () => ({ + apiUrl: 'https://api.example.com', + version: '1.0.0', + features: { + darkMode: true, + analytics: false + } + }) +}); + +// No need to add to providers array - available everywhere! +@Component({ + selector: 'app-header', + template: `

Version: {{ config.version }}

` +}) +export class HeaderComponent { + config = inject(APP_CONFIG); // Automatically available +} +``` + +### When to use InjectionToken with factory functions + +InjectionToken with factory functions is ideal when you can't use a class but need to provide dependencies globally: + +```ts +// 📁 /app/logger.token.ts +import { InjectionToken, inject } from '@angular/core'; +import { APP_CONFIG } from './config.token'; + +// Logger function type +export type LoggerFn = (level: string, message: string) => void; + +// Global logger function with dependencies +export const LOGGER_FN = new InjectionToken('logger.function', { + providedIn: 'root', + factory: () => { + const config = inject(APP_CONFIG); + + return (level: string, message: string) => { + if (config.features.logging !== false) { + console[level](`[${new Date().toISOString()}] ${message}`); + } + }; + } +}); + +// 📁 /app/storage.token.ts +// Providing browser APIs as tokens +export const LOCAL_STORAGE = new InjectionToken('localStorage', { + // providedIn: 'root' is configured as the default + factory: () => window.localStorage +}); + +export const SESSION_STORAGE = new InjectionToken('sessionStorage', { + providedIn: 'root', + factory: () => window.sessionStorage +}); + +// 📁 /app/feature-flags.token.ts +// Complex configuration with runtime logic +export const FEATURE_FLAGS = new InjectionToken>('feature.flags', { + providedIn: 'root', + factory: () => { + const flags = new Map(); + + // Parse from environment or URL params + const urlParams = new URLSearchParams(window.location.search); + const enableBeta = urlParams.get('beta') === 'true'; + + flags.set('betaFeatures', enableBeta); + flags.set('darkMode', true); + flags.set('newDashboard', false); + + return flags; + } +}); +``` + +This approach offers several advantages: + +- **No manual provider configuration needed** - Works just like `providedIn: 'root'` for services +- **Tree-shakeable** - Only included if actually used +- **Type-safe** - Full TypeScript support for non-class values +- **Can inject other dependencies** - Factory functions can use `inject()` to access other services + +## Understanding manual provider configuration + +When you need more control than `providedIn: 'root'` offers, you can manually configure providers. Manual configuration through the `providers` array is useful when: + +1. **The service doesn't have `providedIn`** - Services without automatic provision must be manually provided +2. **You want a new instance** - To create a separate instance at the component/directive level instead of using the shared one +3. **You need runtime configuration** - When service behavior depends on runtime values +4. **You're providing non-class values** - Configuration objects, functions, or primitive values + +### Example: Service without `providedIn` + +```ts +import { Injectable, Component, inject } from '@angular/core'; + +// Service without providedIn +@Injectable() +export class LocalDataStore { + private data: string[] = []; + + addData(item: string) { + this.data.push(item); + } +} + +// Component must provide it +@Component({ + selector: 'app-example', + // A provider is required here because the `LocalDataStore` service has no providedIn. + providers: [LocalDataStore], + template: `...` +}) +export class ExampleComponent { + dataStore = inject(LocalDataStore); +} +``` + +### Example: Creating component-specific instances + +Services with `providedIn: 'root'` can be overridden at the component level. This ties the instance of the service to the life of a component. As a result, when the component gets destroyed, the provided service is also destroyed as well. + +```ts +import { Injectable, Component, inject } from '@angular/core'; + +@Injectable({ providedIn: 'root' }) +export class DataStore { + private data: ListItem[] = []; +} + +// This component gets its own instance +@Component({ + selector: 'app-isolated', + // Creates new instance of `DataStore` rather than using the root-provided instance. + providers: [DataStore], + template: `...` +}) +export class IsolatedComponent { + dataStore = inject(DataStore); // Component-specific instance +} +``` + +## Injector hierarchy in Angular + +Angular's dependency injection system is hierarchical. When a component requests a dependency, Angular starts with that component's injector and walks up the tree until it finds a provider for that dependency. Each component in your application tree can have its own injector, and these injectors form a hierarchy that mirrors your component tree. + +This hierarchy enables: + +- **Scoped instances**: Different parts of your app can have different instances of the same service +- **Override behavior**: Child components can override providers from parent components +- **Memory efficiency**: Services are only instantiated where needed + +In Angular, any element with a component or directive can provide values to all of its descendants. + +```mermaid +graph TD + subgraph platform + subgraph root + direction TB + A[SocialApp] --> B[UserProfile] + A --> C[FriendList] + C --> D[FriendEntry] + end + end +``` + +In the example above: + +1. `SocialApp` can provide values for `UserProfile` and `FriendList` +2. `FriendList` can provide values for injection to `FriendEntry`, but cannot provide values for injection in `UserProfile` because it's not part of the tree + +## Declaring a provider + +Think of Angular's dependency injection system as a hash map or dictionary. Each provider configuration object defines a key-value pair: + +- **Key (Provider identifier)**: The unique identifier you use to request a dependency +- **Value**: What Angular should return when that token is requested + +When manually providing dependencies, you typically see this shorthand syntax: + +```angular-ts +import { Component } from '@angular/core'; +import { LocalService } from './local-service'; + +@Component({ + selector: 'app-example', + providers: [LocalService] // Service without providedIn +}) +export class ExampleComponent { } +``` + +This is actually a shorthand for a more detailed provider configuration: + +```ts +{ + // This is the shorthand version + providers: [LocalService], + + // This is the full version + providers: [ + { provide: LocalService, useClass: LocalService } + ] +} +``` + +### Provider configuration object + +Every provider configuration object has two primary parts: + +1. **Provider identifier**: The unique key that Angular uses to get the dependency (set via the `provide` property) +2. **Value**: The actual dependency that you want Angular to fetch, configured with different keys based on the desired type: + - `useClass` - Provides a JavaScript class + - `useValue` - Provides a static value + - `useFactory` - Provides a factory function that returns the value + - `useExisting` - Provides an alias to an existing provider + +### Provider identifiers + +Provider identifiers allow Angular's dependency injection (DI) system to retrieve a dependency through a unique ID. You can generate provider identifiers in two ways: + +1. [Class names](#class-names) +2. [Injection tokens](#injection-tokens) + +#### Class names + +Class name use the imported class directly as the identifier: + +```angular-ts +import { Component } from '@angular/core'; +import { LocalService } from './local-service'; + +@Component({ + selector: 'app-example', + providers: [ + { provide: LocalService, useClass: LocalService } + ] +}) +export class ExampleComponent { /* ... */ } +``` + +The class serves as both the identifier and the implementation, which is why Angular provides the shorthand `providers: [LocalService]`. + +#### Injection tokens + +Angular provides a built-in [`InjectionToken`](api/core/InjectionToken) class that creates a unique object reference for injectable values or when you want to provide multiple implementations of the same interface. + +```ts +// 📁 /app/tokens.ts +import { InjectionToken } from '@angular/core'; +import { DataService } from './data-service.interface'; + +export const DATA_SERVICE_TOKEN = new InjectionToken('DataService'); +``` + +NOTE: The string `'DataService'` is a description used purely for debugging purposes. Angular identifies the token by its object reference, not this string. + +Use the token in your provider configuration: + +```angular-ts +import { Component, inject } from '@angular/core'; +import { LocalDataService } from './local-data-service'; +import { DATA_SERVICE_TOKEN } from './tokens'; + +@Component({ + selector: 'app-example', + providers: [ + { provide: DATA_SERVICE_TOKEN, useClass: LocalDataService } + ] +}) +export class ExampleComponent { + private dataService = inject(DATA_SERVICE_TOKEN); +} +``` + +#### Can TypeScript interfaces be identifiers for injection? + +TypeScript interfaces cannot be used for injection because they don't exist at runtime: + +```ts +// ❌ This won't work! +interface DataService { + getData(): string[]; +} + +// Interfaces disappear after TypeScript compilation +@Component({ + providers: [ + { provide: DataService, useClass: LocalDataService } // Error! + ] +}) +export class ExampleComponent { + private dataService = inject(DataService); // Error! +} + +// ✅ Use InjectionToken instead +export const DATA_SERVICE_TOKEN = new InjectionToken('DataService'); + +@Component({ + providers: [ + { provide: DATA_SERVICE_TOKEN, useClass: LocalDataService } + ] +}) +export class ExampleComponent { + private dataService = inject(DATA_SERVICE_TOKEN); // Works! +} +``` + +The InjectionToken provides a runtime value that Angular's DI system can use, while still maintaining type safety through TypeScript's generic type parameter. + +### Provider value types + +#### useClass + +`useClass` provides a JavaScript class as a dependency. This is the default when using the shorthand syntax: + +```ts +// Shorthand +providers: [DataService] + +// Full syntax +providers: [ + { provide: DataService, useClass: DataService } +] + +// Different implementation +providers: [ + { provide: DataService, useClass: MockDataService } +] + +// Conditional implementation +providers: [ + { + provide: StorageService, + useClass: environment.production ? CloudStorageService : LocalStorageService + } +] +``` + +#### Practical example: Logger substitution + +You can substitute implementations to extend functionality: + +```ts +import { Injectable, Component, inject } from '@angular/core'; + +// Base logger +@Injectable() +export class Logger { + log(message: string) { + console.log(message); + } +} + +// Enhanced logger with timestamp +@Injectable() +export class BetterLogger extends Logger { + override log(message: string) { + super.log(`[${new Date().toISOString()}] ${message}`); + } +} + +// Logger that includes user context +@Injectable() +export class EvenBetterLogger extends Logger { + private userService = inject(UserService); + + override log(message: string) { + const name = this.userService.user.name; + super.log(`Message to ${name}: ${message}`); + } +} + +// In your component +@Component({ + selector: 'app-example', + providers: [ + UserService, // EvenBetterLogger needs this + { provide: Logger, useClass: EvenBetterLogger } + ] +}) +export class ExampleComponent { + private logger = inject(Logger); // Gets EvenBetterLogger instance +} +``` + +#### useValue + +`useValue` provides any JavaScript data type as a static value: + +```ts +providers: [ + { provide: API_URL_TOKEN, useValue: 'https://api.example.com' }, + { provide: MAX_RETRIES_TOKEN, useValue: 3 }, + { provide: FEATURE_FLAGS_TOKEN, useValue: { darkMode: true, beta: false } } +] +``` + +IMPORTANT: TypeScript types and interfaces cannot serve as dependency values. They exist only at compile-time. + +#### Practical example: Application configuration + +A common use case for `useValue` is providing application configuration: + +```ts +// Define configuration interface +export interface AppConfig { + apiUrl: string; + appTitle: string; + features: { + darkMode: boolean; + analytics: boolean; + }; +} + +// Create injection token +export const APP_CONFIG = new InjectionToken('app.config'); + +// Define configuration +const appConfig: AppConfig = { + apiUrl: 'https://api.example.com', + appTitle: 'My Application', + features: { + darkMode: true, + analytics: false + } +}; + +// Provide in bootstrap +bootstrapApplication(AppComponent, { + providers: [ + { provide: APP_CONFIG, useValue: appConfig } + ] +}); + +// Use in component +@Component({ + selector: 'app-header', + template: `

{{ title }}

` +}) +export class HeaderComponent { + private config = inject(APP_CONFIG); + title = this.config.appTitle; +} +``` + +#### useFactory + +`useFactory` provides a function that generates a new value for injection: + +```ts +export const loggerFactory = (config: AppConfig) => { + return new LoggerService(config.logLevel, config.endpoint); +}; + +providers: [ + { + provide: LoggerService, + useFactory: loggerFactory, + deps: [APP_CONFIG] // Dependencies for the factory function + } +] +``` + +You can mark factory dependencies as optional: + +```ts +import { Optional } from '@angular/core'; + +providers: [ + { + provide: MyService, + useFactory: (required: RequiredService, optional?: OptionalService) => { + return new MyService(required, optional || new DefaultService()); + }, + deps: [RequiredService, [new Optional(), OptionalService]] + } +] +``` + +#### Practical example: Configuration-based API client + +Here's a complete example showing how to use a factory to create a service with runtime configuration: + +```ts +// Service that needs runtime configuration +class ApiClient { + constructor( + private http: HttpClient, + private baseUrl: string, + private rateLimitMs: number + ) {} + + async fetchData(endpoint: string) { + // Apply rate limiting based on user tier + await this.applyRateLimit(); + return this.http.get(`${this.baseUrl}/${endpoint}`); + } + + private async applyRateLimit() { + // Simplified example - real implementation would track request timing + return new Promise(resolve => setTimeout(resolve, this.rateLimitMs)); + } +} + +// Factory function that configures based on user tier +import { inject } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +const apiClientFactory = () => { + const http = inject(HttpClient); + const userService = inject(UserService); + + // Assuming userService provides these values + const baseUrl = userService.getApiBaseUrl(); + const rateLimitMs = userService.getRateLimit(); + + return new ApiClient(http, baseUrl, rateLimitMs); +}; + +// Provider configuration +export const apiClientProvider = { + provide: ApiClient, + useFactory: apiClientFactory +}; + +// Usage in component +@Component({ + selector: 'app-dashboard', + providers: [apiClientProvider] +}) +export class DashboardComponent { + private apiClient = inject(ApiClient); +} +``` + +#### useExisting + +`useExisting` creates an alias for a provider that was already defined. Both tokens return the same instance: + +```ts +providers: [ + NewLogger, // The actual service + { provide: OldLogger, useExisting: NewLogger } // The alias +] +``` + +IMPORTANT: Don't confuse `useExisting` with `useClass`. `useClass` creates separate instances, while `useExisting` ensures you get the same singleton instance. + +### Multiple providers + +Use the `multi: true` flag when multiple providers contribute values to the same token: + +```ts +export const INTERCEPTOR_TOKEN = new InjectionToken('interceptors'); + +providers: [ + { provide: INTERCEPTOR_TOKEN, useClass: AuthInterceptor, multi: true }, + { provide: INTERCEPTOR_TOKEN, useClass: LoggingInterceptor, multi: true }, + { provide: INTERCEPTOR_TOKEN, useClass: RetryInterceptor, multi: true } +] +``` + +When you inject `INTERCEPTOR_TOKEN`, you'll receive an array containing instances of all three interceptors. + +## Where can you specify providers? + +Angular offers several levels where you can register providers, each with different implications for scope, lifecycle, and performance: + +- [**Application bootstrap**](#application-bootstrap) - Global singletons available everywhere +- [**On an element (component or directive)**](#component-or-directive-providers) - Isolated instances for specific component trees +- [**Route**](#route-providers) - Feature-specific services for lazy-loaded modules + +### Application bootstrap + +Use application-level providers in `bootstrapApplication` when: + +- **The service is used across multiple feature areas** - Services like HTTP clients, logging, or authentication that many parts of your app need +- **You want a true singleton** - One instance shared by the entire application +- **The service has no component-specific configuration** - General-purpose utilities that work the same everywhere +- **You're providing global configuration** - API endpoints, feature flags, or environment settings + +```ts +// main.ts +bootstrapApplication(AppComponent, { + providers: [ + { provide: API_BASE_URL, useValue: 'https://api.example.com' }, + { provide: INTERCEPTOR_TOKEN, useClass: AuthInterceptor, multi: true }, + LoggingService, // Used throughout the app + { provide: ErrorHandler, useClass: GlobalErrorHandler } + ] +}); +``` + +**Benefits:** + +- Single instance reduces memory usage +- Available everywhere without additional setup +- Easier to manage global state + +**Drawbacks:** + +- Always included in your JavaScript bundle, even if the value is never injected +- Cannot be easily customized per feature +- Harder to test individual components in isolation + +#### Why provide during bootstrap instead of using `providedIn: 'root'`? + +You might want a provider during bootstrap when: + +- The provider has side-effects (e.g., installing the client-side router) +- The provider requires configuration (e.g., routes) +- You're using Angular's `provideSomething` pattern (e.g., `provideRouter`, `provideHttpClient`) + +### Component or directive providers + +Use component or directive providers when: + +- **The service has component-specific state** - Form validators, component-specific caches, or UI state managers +- **You need isolated instances** - Each component needs its own copy of the service +- **The service is only used by one component tree** - Specialized services that don't need global access +- **You're creating reusable components** - Components that should work independently with their own services + +```angular-ts +// Specialized form component with its own validation service +@Component({ + selector: 'app-advanced-form', + providers: [ + FormValidationService, // Each form gets its own validator + { provide: FORM_CONFIG, useValue: { strictMode: true } } + ] +}) +export class AdvancedFormComponent { } + +// Modal component with isolated state management +@Component({ + selector: 'app-modal', + providers: [ + ModalStateService // Each modal manages its own state + ] +}) +export class ModalComponent { } +``` + +**Benefits:** + +- Better encapsulation and isolation +- Easier to test components individually +- Multiple instances can coexist with different configurations + +**Drawbacks:** + +- New instance created for each component (higher memory usage) +- No shared state between components +- Must be provided wherever needed +- Always included in the same JavaScript bundle as the component or directive, even if the value is never injected + +NOTE: If multiple directives on the same element provide the same token, one will win, but which one is undefined. + +### Route providers + +Use route-level providers for: + +- **Feature-specific services** - Services only needed for particular routes or feature modules +- **Lazy-loaded module dependencies** - Services that should only load with specific features +- **Route-specific configuration** - Settings that vary by application area + +```ts +// routes.ts +export const routes: Routes = [ + { + path: 'admin', + providers: [ + AdminService, // Only loaded with admin routes + { provide: FEATURE_FLAGS, useValue: { adminMode: true } } + ], + loadChildren: () => import('./admin/admin.routes') + }, + { + path: 'shop', + providers: [ + ShoppingCartService, // Isolated shopping state + PaymentService + ], + loadChildren: () => import('./shop/shop.routes') + } +]; +``` + +## Library author patterns + +When creating Angular libraries, you often need to provide flexible configuration options for consumers while maintaining clean APIs. Angular's own libraries demonstrate powerful patterns for achieving this. + +### The `provide` pattern + +Instead of requiring users to manually configure complex providers, library authors can export functions that return provider configurations: + +```ts +// 📁 /libs/analytics/src/providers.ts +import { InjectionToken, Provider, inject } from '@angular/core'; + +// Configuration interface +export interface AnalyticsConfig { + trackingId: string; + enableDebugMode?: boolean; + anonymizeIp?: boolean; +} + +// Internal token for configuration +const ANALYTICS_CONFIG = new InjectionToken('analytics.config'); + +// Main service that uses the configuration +export class AnalyticsService { + private config = inject(ANALYTICS_CONFIG); + + track(event: string, properties?: any) { + // Implementation using config + } +} + +// Provider function for consumers +export function provideAnalytics(config: AnalyticsConfig): Provider[] { + return [ + { provide: ANALYTICS_CONFIG, useValue: config }, + AnalyticsService + ]; +} + +// Usage in consumer app +// main.ts +bootstrapApplication(AppComponent, { + providers: [ + provideAnalytics({ + trackingId: 'GA-12345', + enableDebugMode: !environment.production + }) + ] +}); +``` + +### Advanced provider patterns with options + +For more complex scenarios, you can combine multiple configuration approaches: + +```ts +// 📁 /libs/http-client/src/provider.ts +import { Provider, InjectionToken, inject } from '@angular/core'; + +// Feature flags for optional functionality +export enum HttpFeatures { + Interceptors = 'interceptors', + Caching = 'caching', + Retry = 'retry' +} + +// Configuration interfaces +export interface HttpConfig { + baseUrl?: string; + timeout?: number; + headers?: Record; +} + +export interface RetryConfig { + maxAttempts: number; + delayMs: number; +} + +// Internal tokens +const HTTP_CONFIG = new InjectionToken('http.config'); +const RETRY_CONFIG = new InjectionToken('retry.config'); +const HTTP_FEATURES = new InjectionToken>('http.features'); + +// Core service +class HttpClientService { + private config = inject(HTTP_CONFIG, { optional: true }); + private features = inject(HTTP_FEATURES); + + get(url: string) { + // Use config and check features + } +} + +// Feature services +class RetryInterceptor { + private config = inject(RETRY_CONFIG); + // Retry logic +} + +class CacheInterceptor { + // Caching logic +} + +// Main provider function +export function provideHttpClient( + config?: HttpConfig, + ...features: HttpFeature[] +): Provider[] { + const providers: Provider[] = [ + { provide: HTTP_CONFIG, useValue: config || {} }, + { provide: HTTP_FEATURES, useValue: new Set(features.map(f => f.kind)) }, + HttpClientService + ]; + + // Add feature-specific providers + features.forEach(feature => { + providers.push(...feature.providers); + }); + + return providers; +} + +// Feature configuration functions +export interface HttpFeature { + kind: HttpFeatures; + providers: Provider[]; +} + +export function withInterceptors(...interceptors: any[]): HttpFeature { + return { + kind: HttpFeatures.Interceptors, + providers: interceptors.map(interceptor => ({ + provide: INTERCEPTOR_TOKEN, + useClass: interceptor, + multi: true + })) + }; +} + +export function withCaching(): HttpFeature { + return { + kind: HttpFeatures.Caching, + providers: [CacheInterceptor] + }; +} + +export function withRetry(config: RetryConfig): HttpFeature { + return { + kind: HttpFeatures.Retry, + providers: [ + { provide: RETRY_CONFIG, useValue: config }, + RetryInterceptor + ] + }; +} + +// Consumer usage with multiple features +bootstrapApplication(AppComponent, { + providers: [ + provideHttpClient( + { baseUrl: 'https://api.example.com' }, + withInterceptors(AuthInterceptor, LoggingInterceptor), + withCaching(), + withRetry({ maxAttempts: 3, delayMs: 1000 }) + ) + ] +}); +``` + +### Why use provider functions instead of direct configuration? + +Provider functions offer several advantages for library authors: + +1. **Encapsulation** - Internal tokens and implementation details remain private +2. **Type safety** - TypeScript ensures correct configuration at compile time +3. **Flexibility** - Easily compose features with `with*` pattern +4. **Future-proofing** - Internal implementation can change without breaking consumers +5. **Consistency** - Aligns with Angular's own patterns (`provideRouter`, `provideHttpClient`, etc.) + +This pattern is extensively used in Angular's own libraries and is considered a best practice for library authors who need to provide configurable services. diff --git a/adev-ja/src/content/guide/forms/signals/comparison.md b/adev-ja/src/content/guide/forms/signals/comparison.md new file mode 100644 index 0000000000..209e70e06e --- /dev/null +++ b/adev-ja/src/content/guide/forms/signals/comparison.md @@ -0,0 +1,163 @@ +# Comparison with other form approaches + +Angular provides three approaches to building forms: Signal Forms, Reactive Forms, and Template-driven Forms. Each has distinct patterns for managing state, validation, and data flow. This guide helps you understand the differences and choose the right approach for your project. + +NOTE: Signal Forms are [experimental](reference/releases#experimental) as of Angular v21. The API may change before stabilizing. + +## Quick comparison + +| Feature | Signal Forms | Reactive Forms | Template-driven Forms | +| ---------------- | ---------------------------------- | ------------------------------------- | ----------------------- | +| Source of truth | User-defined writable signal model | `FormControl`/`FormGroup` | User model in component | +| Type safety | Inferred from model | Explicit with typed forms | Minimal | +| Validation | Schema with path-based validators | List of validators passed to Controls | Directive-based | +| State management | Signal-based | Observable-based | Angular-managed | +| Setup | Signal + schema function | FormControl tree | NgModel in template | +| Best for | Signal-based apps | Complex forms | Simple forms | +| Learning curve | Medium | Medium-High | Low | +| Status | Experimental (v21+) | Stable | Stable | + +## By example: Login form + +The best way to understand the differences is to see the same form implemented in all three approaches. + + + + + + + +## Understanding the differences + +The three approaches make different design choices that affect how you write and maintain your forms. These differences stem from where each approach stores form state and how it manages validation. + +### Where your form data lives + +The most fundamental difference is where each approach considers the "source of truth" for form values. + +Signal Forms stores data in a writable signal. When you need the current form values, you call the signal: + +```ts +const credentials = this.loginModel(); // { email: '...', password: '...' } +``` + +This keeps your form data in a single reactive container that automatically notifies Angular when values change. The form structure mirrors your data model exactly. + +Reactive Forms stores data inside FormControl and FormGroup instances. You access values through the form hierarchy: + +```ts +const credentials = this.loginForm.value; // { email: '...', password: '...' } +``` + +This separates form state management from your component's data model. The form structure is explicit but requires more setup code. + +Template-driven Forms stores data in component properties. You access values directly: + +```ts +const credentials = { email: this.email, password: this.password }; +``` + +This is the most direct approach but requires manually assembling values when you need them. Angular manages form state through directives in the template. + +### How validation works + +Each approach defines validation rules differently, affecting where your validation logic lives and how you maintain it. + +Signal Forms uses a schema function where you bind validators to field paths: + +```ts +loginForm = form(this.loginModel, (fieldPath) => { + required(fieldPath.email, { message: 'Email is required' }); + email(fieldPath.email, { message: 'Enter a valid email address' }); +}); +``` + +All validation rules live together in one place. The schema function runs once during form creation, and validators execute automatically when field values change. Error messages are part of the validation definition. + +Reactive Forms attaches validators when creating controls: + +```ts +loginForm = new FormGroup({ + email: new FormControl('', [Validators.required, Validators.email]) +}); +``` + +Validators are tied to individual controls in the form structure. This distributes validation across your form definition. Error messages typically live in your template. + +Template-driven Forms uses directive attributes in the template: + +```html + +``` + +Validation rules live in your template alongside the HTML. This keeps validation close to the UI but spreads logic across template and component. + +### Type safety and autocomplete + +TypeScript integration differs significantly between approaches, affecting how much the compiler helps you avoid errors. + +Signal Forms infers types from your model structure: + +```ts +const loginModel = signal({ email: '', password: '' }); +const loginForm = form(loginModel); +// TypeScript knows: loginForm.email exists and returns FieldState +``` + +You define your data shape once in the signal, and TypeScript automatically knows what fields exist and their types. Accessing `loginForm.username` (which doesn't exist) produces a type error. + +Reactive Forms requires explicit type annotations with typed forms: + +```ts +const loginForm = new FormGroup({ + email: new FormControl(''), + password: new FormControl('') +}); +// TypeScript knows: loginForm.controls.email is FormControl +``` + +You specify types for each control individually. TypeScript validates your form structure, but you maintain type information separately from your data model. + +Template-driven Forms offers minimal type safety: + +```ts +email = ''; +password = ''; +// TypeScript only knows these are strings, no form-level typing +``` + +TypeScript understands your component properties but has no knowledge of form structure or validation. You lose compile-time checking for form operations. + +## Choose your approach + +### Use Signal Forms if: + +- You're building new signal-based applications (Angular v21+) +- You want type safety inferred from your model structure +- You're comfortable working with experimental features +- Schema-based validation appeals to you +- Your team is familiar with signals + +### Use Reactive Forms if: + +- You need production-ready stability +- You're building complex, dynamic forms +- You prefer observable-based patterns +- You need fine-grained control over form state +- You're working on an existing reactive forms codebase + +### Use Template-driven Forms if: + +- You're building simple forms (login, contact, search) +- You're doing rapid prototyping +- Your form logic is straightforward +- You prefer keeping form logic in templates +- You're working on an existing template-driven codebase + +## Next steps + +To learn more about each approach: + +- **Signal Forms**: See the [Overview guide](guide/forms/signal-forms/overview) to get started, or dive into [Form Models](guide/forms/signal-forms/models), [Validation](guide/forms/signal-forms/validation), and [Field State Management](guide/forms/signal-forms/field-state-management) +- **Reactive Forms**: See the [Reactive Forms guide](guide/forms/reactive-forms) in Angular documentation +- **Template-driven Forms**: See the [Template-driven Forms guide](guide/forms/template-driven-forms) in Angular documentation diff --git a/adev-ja/src/content/guide/forms/signals/models.md b/adev-ja/src/content/guide/forms/signals/models.md new file mode 100644 index 0000000000..f0f2fc4e67 --- /dev/null +++ b/adev-ja/src/content/guide/forms/signals/models.md @@ -0,0 +1,536 @@ +# Form models + +Form models are the foundation of Signal Forms, serving as the single source of truth for your form data. This guide explores how to create form models, update them, and design them for maintainability. + +NOTE: Form models are distinct from Angular's `model()` signal used for component two-way binding. A form model is a writable signal that stores form data, while `model()` creates inputs/outputs for parent/child component communication. + +## What form models solve + +Forms require managing data that changes over time. Without a clear structure, this data can become scattered across component properties, making it difficult to track changes, validate input, or submit data to a server. + +Form models solve this by centralizing form data in a single writable signal. When the model updates, the form automatically reflects those changes. When users interact with the form, the model updates accordingly. + +## Creating models + +A form model is a writable signal created with Angular's `signal()` function. The signal holds an object that represents your form's data structure. + +```ts +import { Component, signal } from '@angular/core' +import { form, Field } from '@angular/forms/signals' + +@Component({ + selector: 'app-login', + imports: [Field], + template: ` + + + ` +}) +export class LoginComponent { + loginModel = signal({ + email: '', + password: '' + }) + + loginForm = form(this.loginModel) +} +``` + +The `form()` function accepts the model signal and creates a **field tree** - a special object structure that mirrors your model's shape. The field tree is both navigable (access child fields with dot notation like `loginForm.email`) and callable (call a field as a function to access its state). + +The `[field]` directive binds each input element to its corresponding field in the field tree, enabling automatic two-way synchronization between the UI and model. + +### Using TypeScript types + +While TypeScript infers types from object literals, defining explicit types improves code quality and provides better IntelliSense support. + +```ts +interface LoginData { + email: string + password: string +} + +export class LoginComponent { + loginModel = signal({ + email: '', + password: '' + }) + + loginForm = form(this.loginModel) +} +``` + +With explicit types, the field tree provides full type safety. Accessing `loginForm.email` is typed as `FieldTree`, and attempting to access a non-existent property results in a compile-time error. + +```ts +// TypeScript knows this is FieldTree +const emailField = loginForm.email + +// TypeScript error: Property 'username' does not exist +const usernameField = loginForm.username +``` + +### Initializing all fields + +Form models should provide initial values for all fields you want to include in the field tree. + +```ts +// Good: All fields initialized +const userModel = signal({ + name: '', + email: '', + age: 0 +}) + +// Avoid: Missing initial value +const userModel = signal({ + name: '', + email: '' + // age field is not defined - cannot access userForm.age +}) +``` + +For optional fields, explicitly set them to `null` or an empty value: + +```ts +interface UserData { + name: string + email: string + phoneNumber: string | null +} + +const userModel = signal({ + name: '', + email: '', + phoneNumber: null +}) +``` + +Fields set to `undefined` are excluded from the field tree. A model with `{value: undefined}` behaves identically to `{}` - accessing the field returns `undefined` rather than a `FieldTree`. + +### Dynamic field addition + +You can dynamically add fields by updating the model with new properties. The field tree automatically updates to include new fields when they appear in the model value. + +```ts +// Start with just email +const model = signal({ email: '' }) +const myForm = form(model) + +// Later, add a password field +model.update(current => ({ ...current, password: '' })) +// myForm.password is now available +``` + +This pattern is useful when fields become relevant based on user choices or loaded data. + +## Reading model values + +You can access form values in two ways: directly from the model signal, or through individual fields. Each approach serves a different purpose. + +### Reading from the model + +Access the model signal when you need the complete form data, such as during form submission: + +```ts +onSubmit() { + const formData = this.loginModel(); + console.log(formData.email, formData.password); + + // Send to server + await this.authService.login(formData); +} +``` + +The model signal returns the entire data object, making it ideal for operations that work with the complete form state. + +### Reading from field state + +Each field in the field tree is a function. Calling a field returns a `FieldState` object containing reactive signals for the field's value, validation status, and interaction state. + +Access field state when working with individual fields in templates or reactive computations: + +```ts +@Component({ + template: ` +

Current email: {{ loginForm.email().value() }}

+

Password length: {{ passwordLength() }}

+ ` +}) +export class LoginComponent { + loginModel = signal({ email: '', password: '' }) + loginForm = form(this.loginModel) + + passwordLength = computed(() => { + return this.loginForm.password().value().length + }) +} +``` + +Field state provides reactive signals for each field's value, making it suitable for displaying field-specific information or creating derived state. + +TIP: Field state includes many more signals beyond `value()`, such as validation state (e.g., valid, invalid, errors), interaction tracking (e.g., touched, dirty), and visibility (e.g., hidden, disabled). + + + + +## Updating form models programmatically + +Form models update through programmatic mechanisms: + +1. [Replace the entire form model](#replacing-form-models-with-set) with `set()` +2. [Update one or more fields](#update-one-or-more-fields-with-update) with `update()` +3. [Update a single field directly](#update-a-single-field-directly-with-set) through field state + +### Replacing form models with `set()` + +Use `set()` on the form model to replace the entire value: + +```ts +loadUserData() { + this.userModel.set({ + name: 'Alice', + email: 'alice@example.com', + age: 30, + }); +} + +resetForm() { + this.userModel.set({ + name: '', + email: '', + age: 0, + }); +} +``` + +This approach works well when loading data from an API or resetting the entire form. + +### Update one or more fields with `update()` + +Use `update()` to modify specific fields while preserving others: + +```ts +updateEmail(newEmail: string) { + this.userModel.update(current => ({ + ...current, + email: newEmail, + })); +} +``` + +This pattern is useful when you need to change one or more fields based on the current model state. + +### Update a single field directly with `set()` + +Use `set()` on individual field values to directly update the field state: + +```ts +clearEmail() { + this.userForm.email().value.set(''); +} + +incrementAge() { + const currentAge = this.userForm.age().value(); + this.userForm.age().value.set(currentAge + 1); +} +``` + +These are also known as "field-level updates." They automatically propagate to the model signal and keep both in sync. + +### Example: Loading data from an API + +A common pattern involves fetching data and populating the model: + +```ts +export class UserProfileComponent { + userModel = signal({ + name: '', + email: '', + bio: '' + }) + + userForm = form(this.userModel) + private userService = inject(UserService) + + ngOnInit() { + this.loadUserProfile() + } + + async loadUserProfile() { + const userData = await this.userService.getUserProfile() + this.userModel.set(userData) + } +} +``` + +The form fields automatically update when the model changes, displaying the fetched data without additional code. + +## Two-way data binding + +The `[field]` directive creates automatic two-way synchronization between the model, form state, and UI. + +### How data flows + +Changes flow bidirectionally: + +**User input → Model:** + +1. User types in an input element +2. The `[field]` directive detects the change +3. Field state updates +4. Model signal updates + +**Programmatic update → UI:** + +1. Code updates the model with `set()` or `update()` +2. Model signal notifies subscribers +3. Field state updates +4. The `[field]` directive updates the input element + +This synchronization happens automatically. You don't write subscriptions or event handlers to keep the model and UI in sync. + +### Example: Both directions + +```ts +@Component({ + template: ` + + +

Current name: {{ userModel().name }}

+ ` +}) +export class UserComponent { + userModel = signal({ name: '' }) + userForm = form(this.userModel) + + setName(name: string) { + this.userModel.update(current => ({ ...current, name })) + // Input automatically displays 'Bob' + } +} +``` + +When the user types in the input, `userModel().name` updates. When the button is clicked, the input value changes to "Bob". No manual synchronization code is required. + +## Model structure patterns + +Form models can be flat objects or contain nested objects and arrays. The structure you choose affects how you access fields and organize validation. + +### Flat vs nested models + +Flat form models keep all fields at the top level: + +```ts +// Flat structure +const userModel = signal({ + name: '', + email: '', + street: '', + city: '', + state: '', + zip: '' +}) +``` + +Nested models group related fields: + +```ts +// Nested structure +const userModel = signal({ + name: '', + email: '', + address: { + street: '', + city: '', + state: '', + zip: '' + } +}) +``` + +**Use flat structures when:** + +- Fields don't have clear conceptual groupings +- You want simpler field access (`userForm.city` vs `userForm.address.city`) +- Validation rules span multiple potential groups + +**Use nested structures when:** + +- Fields form a clear conceptual group (like an address) +- The grouped data matches your API structure +- You want to validate the group as a unit + +### Working with nested objects + +You can access nested fields by following the object path: + +```ts +const userModel = signal({ + profile: { + firstName: '', + lastName: '' + }, + settings: { + theme: 'light', + notifications: true + } +}) + +const userForm = form(userModel) + +// Access nested fields +userForm.profile.firstName // FieldTree +userForm.settings.theme // FieldTree +``` + +In templates, you bind nested fields the same way as top-level fields: + +```ts +@Component({ + template: ` + + + + + `, +}) +``` + +### Working with arrays + +Models can include arrays for collections of items: + +```ts +const orderModel = signal({ + customerName: '', + items: [{ product: '', quantity: 0, price: 0 }] +}) + +const orderForm = form(orderModel) + +// Access array items by index +orderForm.items[0].product // FieldTree +orderForm.items[0].quantity // FieldTree +``` + +Array items containing objects automatically receive tracking identities, which helps maintain field state even when items change position in the array. This ensures validation state and user interactions persist correctly when arrays are reordered. + + + +## Model design best practices + +Well-designed form models make forms easier to maintain and extend. Follow these patterns when designing your models. + +### Use specific types + +Always define interfaces or types for your models as shown in [Using TypeScript types](#using-typescript-types). Explicit types provide better IntelliSense, catch errors at compile time, and serve as documentation for what data the form contains. + +### Initialize all fields + +Provide initial values for every field in your model: + +```ts +// Good: All fields initialized +const taskModel = signal({ + title: '', + description: '', + priority: 'medium', + completed: false +}) +``` + +```ts +// Avoid: Partial initialization +const taskModel = signal({ + title: '' + // Missing description, priority, completed +}) +``` + +Missing initial values mean those fields won't exist in the field tree, making them inaccessible for form interactions. + +### Keep models focused + +Each model should represent a single form or a cohesive set of related data: + +```ts +// Good: Focused on login +const loginModel = signal({ + email: '', + password: '' +}) +``` + +```ts +// Avoid: Mixing unrelated concerns +const appModel = signal({ + // Login data + email: '', + password: '', + // User preferences + theme: 'light', + language: 'en', + // Shopping cart + cartItems: [] +}) +``` + +Separate models for different concerns makes forms easier to understand and reuse. Create multiple forms if you're managing distinct sets of data. + +### Consider validation requirements + +Design models with validation in mind. Group fields that validate together: + +```ts +// Good: Password fields grouped for comparison +interface PasswordChangeData { + currentPassword: string + newPassword: string + confirmPassword: string +} +``` + +This structure makes cross-field validation (like checking if `newPassword` matches `confirmPassword`) more natural. + +### Plan for initial state + +Consider whether your form starts empty or pre-populated: + +```ts +// Form that starts empty (new user) +const newUserModel = signal({ + name: '', + email: '', +}); + +// Form that loads existing data +const editUserModel = signal({ + name: '', + email: '', +}); + +// Later, in ngOnInit: +ngOnInit() { + this.loadExistingUser(); +} + +async loadExistingUser() { + const user = await this.userService.getUser(this.userId); + this.editUserModel.set(user); +} +``` + +For forms that always start with existing data, you might wait to render the form until data loads in order to avoid a flash of empty fields. + + + diff --git a/adev-ja/src/content/guide/forms/signals/overview.md b/adev-ja/src/content/guide/forms/signals/overview.md new file mode 100644 index 0000000000..fea36bd132 --- /dev/null +++ b/adev-ja/src/content/guide/forms/signals/overview.md @@ -0,0 +1,59 @@ + + + +CRITICAL: Signal Forms are [experimental](/reference/releases#experimental). The API may change in future releases. Avoid using experimental APIs in production applications without understanding the risks. + +Signal Forms is an experimental library that allows you to manage form state in Angular applications by building on the reactive foundation of signals. With automatic two-way binding, type-safe field access, and schema-based validation, Signal Forms help you create robust forms. + +TIP: For a quick introduction to Signal Forms, see the [Signal Forms essentials guide](essentials/signal-forms). + +## Why Signal Forms? + +Building forms in web applications involves managing several interconnected concerns: tracking field values, validating user input, handling error states, and keeping the UI synchronized with your data model. Managing these concerns separately creates boilerplate code and complexity. + +Signal Forms address these challenges by: + +- **Synchronizing state automatically** - Automatically syncs the form data model with bound form fields +- **Providing type safety** - Supports fully type safe schemas & bindings between your UI controls and data model +- **Centralizing validation logic** - Define all validation rules in one place using a validation schema + +Signal Forms work best in new applications built with signals. If you're working with an existing application that uses reactive forms, or if you need production stability guarantees, reactive forms remain a solid choice. + + + + +## Prerequisites + +Signal Forms require: + +- Angular v21 or higher + +## Setup + +Signal Forms are already included in the `@angular/forms` package. Import the necessary functions and directives from `@angular/forms/signals`: + +```ts +import { form, Field, required, email } from '@angular/forms/signals' +``` + +The `Field` directive must be imported into any component that binds form fields to HTML inputs: + +```ts +@Component({ + // ... + imports: [Field], +}) +``` + + + diff --git a/adev-ja/src/content/guide/testing/karma.md b/adev-ja/src/content/guide/testing/karma.md new file mode 100644 index 0000000000..064b617c28 --- /dev/null +++ b/adev-ja/src/content/guide/testing/karma.md @@ -0,0 +1,199 @@ +# Testing with Karma and Jasmine + +While [Vitest](https://vitest.dev) is the default test runner for new Angular projects, [Karma](https://karma-runner.github.io) is still a supported and widely used test runner. This guide provides instructions for testing your Angular application using the Karma test runner with the [Jasmine](https://jasmine.github.io) testing framework. + +## Setting Up Karma and Jasmine + +You can set up Karma and Jasmine for a new project or add it to an existing one. + +### For New Projects + +To create a new project with Karma and Jasmine pre-configured, run the `ng new` command with the `--test-runner=karma` option: + +```shell +ng new my-karma-app --test-runner=karma +``` + +### For Existing Projects + +To add Karma and Jasmine to an existing project, follow these steps: + +1. **Install the necessary packages:** + + + + npm install --save-dev karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine + + + yarn add --dev karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine + + + pnpm add -D karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine + + + bun add --dev karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine + + + +2. **Configure the test runner in `angular.json`:** + + In your `angular.json` file, find the `test` target and set the `runner` option to `karma`: + + ```json + { + // ... + "projects": { + "your-project-name": { + // ... + "architect": { + "test": { + "builder": "@angular/build:unit-test", + "options": { + "runner": "karma", + // ... other options + } + } + } + } + } + } + ``` + +3. **Update `tsconfig.spec.json` for Jasmine types:** + + To ensure TypeScript recognizes global testing functions like `describe` and `it`, add `"jasmine"` to the `types` array in your `tsconfig.spec.json`: + + ```json + { + // ... + "compilerOptions": { + // ... + "types": [ + "jasmine" + ] + }, + // ... + } + ``` + +## Running Tests + +Once your project is configured, run the tests using the [`ng test`](cli/test) command: + +```shell +ng test +``` + +The `ng test` command builds the application in _watch mode_ and launches the [Karma test runner](https://karma-runner.github.io). + +The console output looks like below: + +```shell + +02 11 2022 09:08:28.605:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/ +02 11 2022 09:08:28.607:INFO [launcher]: Launching browsers Chrome with concurrency unlimited +02 11 2022 09:08:28.620:INFO [launcher]: Starting browser Chrome +02 11 2022 09:08:31.312:INFO [Chrome]: Connected on socket -LaEYvD2R7MdcS0-AAAB with id 31534482 +Chrome: Executed 3 of 3 SUCCESS (0.193 secs / 0.172 secs) +TOTAL: 3 SUCCESS + +``` + +The test output is displayed in the browser using [Karma Jasmine HTML Reporter](https://github.com/dfederm/karma-jasmine-html-reporter). + +Jasmine HTML Reporter in the browser + +Click on a test row to re-run just that test or click on a description to re-run the tests in the selected test group ("test suite"). + +Meanwhile, the `ng test` command is watching for changes. To see this in action, make a small change to a source file and save. The tests run again, the browser refreshes, and the new test results appear. + +## Configuration + +The Angular CLI takes care of Jasmine and Karma configuration for you. It constructs the full configuration in memory, based on options specified in the `angular.json` file. + +### Customizing Karma Configuration + +If you want to customize Karma, you can create a `karma.conf.js` by running the following command: + +```shell +ng generate config karma +``` + +HELPFUL: Read more about Karma configuration in the [Karma configuration guide](http://karma-runner.github.io/6.4/config/configuration-file.html). + +### Setting the Test Runner in `angular.json` + +To explicitly set Karma as the test runner for your project, locate the `test` target in your `angular.json` file and set the `runner` option to `karma`: + +```json +{ + // ... + "projects": { + "your-project-name": { + // ... + "architect": { + "test": { + "builder": "@angular/build:unit-test", + "options": { + "runner": "karma", + // ... other options + } + } + } + } + } +} +``` + +## Code coverage enforcement + +To enforce a minimum code coverage level, you can use the `check` property in the `coverageReporter` section of your `karma.conf.js` file. + +For example, to require a minimum of 80% coverage: + +```javascript +coverageReporter: { + dir: require('path').join(__dirname, './coverage/'), + subdir: '.', + reporters: [ + { type: 'html' }, + { type: 'text-summary' } + ], + check: { + global: { + statements: 80, + branches: 80, + functions: 80, + lines: 80 + } + } +} +``` + +This will cause the test run to fail if the specified coverage thresholds are not met. + +## Testing in continuous integration + +To run your Karma tests in a CI environment, use the following command: + +```shell +ng test --no-watch --no-progress --browsers=ChromeHeadless +``` + +NOTE: The `--no-watch` and `--no-progress` flags are crucial for Karma in CI environments to ensure tests run once and exit cleanly. The `--browsers=ChromeHeadless` flag is also essential for running tests in a browser environment without a graphical interface. + +## Debugging tests + +If your tests aren't working as you expect, you can inspect and debug them in the browser. + +To debug an application with the Karma test runner: + +1. Reveal the Karma browser window. See [Set up for testing](guide/testing/overview#set-up-for-testing) if you need help with this step. +2. Click the **DEBUG** button to open a new browser tab and re-run the tests. +3. Open the browser's **Developer Tools**. On Windows, press `Ctrl-Shift-I`. On macOS, press `Command-Option-I`. +4. Pick the **Sources** section. +5. Press `Control/Command-P`, and then start typing the name of your test file to open it. +6. Set a breakpoint in the test. +7. Refresh the browser, and notice how it stops at the breakpoint. + +Karma debugging diff --git a/adev-ja/src/content/guide/testing/migrating-to-vitest.md b/adev-ja/src/content/guide/testing/migrating-to-vitest.md new file mode 100644 index 0000000000..eda97ef9d7 --- /dev/null +++ b/adev-ja/src/content/guide/testing/migrating-to-vitest.md @@ -0,0 +1,229 @@ +# Migrating from Karma to Vitest + +The Angular CLI uses [Vitest](https://vitest.dev/) as the default unit test runner for new projects. This guide provides instructions for migrating an existing project from Karma and Jasmine to Vitest. + +IMPORTANT: Migrating an existing project to Vitest is considered experimental. This process also requires the use of the `application` build system, which is the default for all newly created projects. + +## Manual migration steps + +Before using the automated refactoring schematic, you must manually update your project to use the Vitest test runner. + +### 1. Install dependencies + +Install `vitest` and a DOM emulation library. While browser testing is still possible (see [step 5](#5-configure-browser-mode-optional)), Vitest uses a DOM emulation library by default to simulate a browser environment within Node.js for faster test execution. The CLI automatically detects and uses `happy-dom` if it's installed; otherwise, it falls back to `jsdom`. You must have one of these packages installed. + + + + npm install --save-dev vitest jsdom + + + yarn add --dev vitest jsdom + + + pnpm add -D vitest jsdom + + + bun add --dev vitest jsdom + + + +### 2. Update `angular.json` + +In your `angular.json` file, find the `test` target for your project and change the `builder` to `@angular/build:unit-test`. + +```json +{ + "projects": { + "your-project-name": { + "architect": { + "test": { + "builder": "@angular/build:unit-test" + } + } + } + } +} +``` + +The `unit-test` builder defaults to `"tsConfig": "tsconfig.spec.json"` and `"buildTarget": "::development"`. You can explicitly set these options if your project requires different values. For example, if the `development` build configuration is missing or you need different options for testing, you can create and use a `testing` or similarly named build configuration for `buildTarget`. + +The `@angular/build:karma` builder previously allowed build options (like `polyfills`, `assets`, or `styles`) to be configured directly within the `test` target. The new `@angular/build:unit-test` builder does not support this. If your test-specific build options differ from your existing `development` build configuration, you must move them to a dedicated build target configuration. If your test build options already match your `development` build configuration, no action is needed. + +### 3. Handle custom `karma.conf.js` configurations + +Custom configurations in `karma.conf.js` are not automatically migrated. Before deleting your `karma.conf.js` file, review it for any custom settings that need to be migrated. + +Many Karma options have equivalents in Vitest that can be set in a custom Vitest configuration file (e.g., `vitest.config.ts`) and linked to your `angular.json` via the `runnerConfig` option. + +Common migration paths include: + +- **Reporters**: Karma reporters must be replaced with Vitest-compatible reporters. These can often be configured directly in your `angular.json` under the `test.options.reporters` property. For more advanced configurations, use a custom `vitest.config.ts` file. +- **Plugins**: Karma plugins may have Vitest equivalents that you will need to find and install. Note that code coverage is a first-class feature in the Angular CLI and can be enabled with `ng test --coverage`. +- **Custom Browser Launchers**: These are replaced by the `browsers` option in `angular.json` and the installation of a browser provider like `@vitest/browser-playwright`. + +For other settings, consult the official [Vitest documentation](https://vitest.dev/config/). + +### 4. Remove Karma and `test.ts` files + +You can now delete `karma.conf.js` and `src/test.ts` from your project and uninstall the Karma-related packages. The following commands are based on the packages installed in a new Angular CLI project; your project may have other Karma-related packages to remove. + + + + npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter + + + yarn remove karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter + + + pnpm remove karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter + + + bun remove karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter + + + +### 5. Configure browser mode (optional) + +If you need to run tests in a real browser, you must install a browser provider and configure your `angular.json`. + +**Install a browser provider:** + +Choose one of the following browser providers based on your needs: + +- **Playwright**: `@vitest/browser-playwright` for Chromium, Firefox, and WebKit. +- **WebdriverIO**: `@vitest/browser-webdriverio` for Chrome, Firefox, Safari, and Edge. +- **Preview**: `@vitest/browser-preview` for Webcontainer environments (like StackBlitz). + + + + npm install --save-dev @vitest/browser-playwright + + + yarn add --dev @vitest/browser-playwright + + + pnpm add -D @vitest/browser-playwright + + + bun add --dev @vitest/browser-playwright + + + +**Update `angular.json` for browser mode:** + +Add the `browsers` option to your `test` target's options. The browser name depends on the provider you installed (e.g., `chromium` for Playwright, `chrome` for WebdriverIO). + +```json +{ + "projects": { + "your-project-name": { + "architect": { + "test": { + "builder": "@angular/build:unit-test", + "options": { + "browsers": ["chromium"] + } + } + } + } + } +} +``` + +Headless mode is enabled automatically if the `CI` environment variable is set or if a browser name includes "Headless" (e.g., `ChromeHeadless`). Otherwise, tests will run in a headed browser. + +## Automated test refactoring with schematics + +IMPORTANT: The `refactor-jasmine-vitest` schematic is experimental and may not cover all possible test patterns. Always review the changes made by the schematic. + +The Angular CLI provides the `refactor-jasmine-vitest` schematic to automatically refactor your Jasmine tests to use Vitest. + +### Overview + +The schematic automates the following transformations in your test files (`.spec.ts`): + +- Converts `fit` and `fdescribe` to `it.only` and `describe.only`. +- Converts `xit` and `xdescribe` to `it.skip` and `describe.skip`. +- Converts `spyOn` calls to the equivalent `vi.spyOn`. +- Replaces `jasmine.objectContaining` with `expect.objectContaining`. +- Replaces `jasmine.any` with `expect.any`. +- Replaces `jasmine.createSpy` with `vi.fn`. +- Updates `beforeAll`, `beforeEach`, `afterAll`, and `afterEach` to their Vitest equivalents. +- Converts `fail()` to Vitest's `vi.fail()`. +- Adjusts expectations to match Vitest APIs +- Adds TODO comments for code that cannot be automatically converted + +The schematic **does not** perform the following actions: + +- It does not install `vitest` or other related dependencies. +- It does not change your `angular.json` to use the Vitest builder or migrate any build options (like `polyfills` or `styles`) from the `test` target. +- It does not remove `karma.conf.js` or `test.ts` files. +- It does not handle complex or nested spy scenarios, which may require manual refactoring. + +### Running the schematic + +Once your project is configured for Vitest, you can run the schematic to refactor your test files. + +To refactor **all** test files in your default project, run: + +```bash +ng g @schematics/angular:refactor-jasmine-vitest +``` + +### Options + +You can use the following options to customize the schematic's behavior: + +| Option | Description | +| :----------------------- | :-------------------------------------------------------------------------------------------------- | +| `--project ` | Specify the project to refactor in a multi-project workspace.
Example: `--project=my-lib` | +| `--include ` | Refactor only a specific file or directory.
Example: `--include=src/app/app.component.spec.ts` | +| `--file-suffix ` | Specify a different file suffix for test files.
Example: `--file-suffix=.test.ts` | +| `--add-imports` | Add explicit `vitest` imports if you have disabled globals in your Vitest configuration. | +| `--verbose` | See detailed logging of all transformations applied. | + +### After migrating + +After the schematic completes, it's a good practice to: + +1. **Run your tests**: Execute `ng test` to ensure that all tests still pass after the refactoring. +2. **Review the changes**: Look over the changes made by the schematic, paying close attention to any complex tests, especially those with intricate spies or mocks, as they may require further manual adjustments. + +The `ng test` command builds the application in _watch mode_ and launches the configured runner. Watch mode is enabled by default when using an interactive terminal and not running on CI. + +## Configuration + +The Angular CLI takes care of the Vitest configuration for you, constructing the full configuration in memory based on options in `angular.json`. + +### Custom Vitest configuration + +IMPORTANT: While using a custom configuration enables advanced options, the Angular team does not provide direct support for the specific contents of the configuration file or for any third-party plugins used within it. The CLI will also override certain properties (`test.projects`, `test.include`) to ensure proper operation. + +You can provide a custom Vitest configuration file to override the default settings. For a full list of available options, see the official [Vitest documentation](https://vitest.dev/config/). + +**1. Direct path:** +Provide a direct path to a Vitest configuration file in your `angular.json`: + +```json +{ + "projects": { + "your-project-name": { + "architect": { + "test": { + "builder": "@angular/build:unit-test", + "options": { "runnerConfig": "vitest.config.ts" } + } + } + } + } +} +``` + +**2. Automatic search for base configuration:** +If you set `runnerConfig` to `true`, the builder will automatically search for a shared `vitest-base.config.*` file in your project and workspace roots. + +## Bug reports + +Report issues and feature requests on [GitHub](https://github.com/angular/angular-cli/issues). + +Please provide a minimal reproduction where possible to aid the team in addressing issues. diff --git a/adev-ja/src/content/introduction/essentials/signal-forms.md b/adev-ja/src/content/introduction/essentials/signal-forms.md new file mode 100644 index 0000000000..3bf1b4b5e3 --- /dev/null +++ b/adev-ja/src/content/introduction/essentials/signal-forms.md @@ -0,0 +1,254 @@ + +Signal Forms is built on Angular signals to provide a reactive, type-safe way to manage form state. + + +Signal Forms manage form state using Angular signals to provide automatic synchronization between your data model and the UI. + +This guide walks you through the core concepts to create forms with Signal Forms. Here's how it works: + +## Creating your first form + +### 1. Create a form model + +Every form starts by creating a signal that holds your form's data model: + +```ts +interface LoginData { + email: string; + password: string; +} + +const loginModel = signal({ + email: '', + password: '', +}); +``` + +### 2. Pass the form model to `form()` + +Then, you pass your form model into the `form()` function to create a **field tree** - an object structure that mirrors your model's shape, allowing you to access fields with dot notation: + +```ts +form(loginModel); + +// Access fields directly by property name +loginForm.email +loginForm.password +``` + +### 3. Bind inputs with `[field]` directive + +Next, you bind your HTML inputs to the form using the `[field]` directive, which creates two-way binding between them: + +```html + + +``` + +As a result, user changes (such as typing in the field) automatically updates the form, and any programmatic changes update the displayed value as well: + +```ts +// Update the value programmatically +loginForm.email().value.set('alice@wonderland.com'); + +// The model signal is also updated +console.log(loginModel().email); // 'alice@wonderland.com' +``` + +NOTE: The `[field]` directive also syncs field state for attributes like `required`, `disabled`, and `readonly` when appropriate. + +### 4. Read form field values with `value()` + +You can access field state by calling the field as a function. This returns a `FieldState` object containing reactive signals for the field's value, validation status, and interaction state: + +```ts +loginForm.email() // Returns FieldState with value(), valid(), touched(), etc. +``` + +To read the field's current value, access the `value()` signal: + +```html + +

Email: {{ loginForm.email().value() }}

+``` + +```ts +// Get the current value +const currentEmail = loginForm.email().value(); +``` + +Here's a complete example: + + + + + + + +## Basic usage + +The `[field]` directive works with all standard HTML input types. Here are the most common patterns: + +### Text inputs + +Text inputs work with various `type` attributes and textareas: + +```html + + + +``` + +#### Numbers + +Number inputs automatically convert between strings and numbers: + +```html + + +``` + +#### Date and time + +Date inputs store values as `YYYY-MM-DD` strings, and time inputs use `HH:mm` format: + +```html + + + +``` + +If you need to convert date strings to Date objects, you can do so by passing the field value into `Date()`: + +```ts +const dateObject = new Date(form.eventDate().value()); +``` + +#### Multiline text + +Textareas work the same way as text inputs: + +```html + + +``` + +### Checkboxes + +Checkboxes bind to boolean values: + +```html + + +``` + +#### Multiple checkboxes + +For multiple options, create a separate boolean `field` for each: + +```html + + +``` + +### Radio buttons + +Radio buttons work similarly to checkboxes. As long as the radio buttons use the same `[field]` value, Signal Forms will automatically bind the same `name` attribute to all of them: + +```html + + +``` + +When a user selects a radio button, the form `field` stores the value from that radio button's `value` attribute. For example, selecting "Premium" sets `form.plan().value()` to `"premium"`. + +### Select dropdowns + +Select elements work with both static and dynamic options: + +```html + + + + + +``` + +NOTE: Multiple select (` provide built-in accessibility for straightforward use cases +- **Rapid prototyping** - When validating concepts quickly, pre-styled component libraries reduce initial development time + +## Next steps + +Explore the component guides to find the pattern that fits your needs: + +**Search and selection** + +- Autocomplete - Search and filter options as users type +- Listbox - Select one or multiple items from a list +- Select - Choose one option from a list of options +- Multiselect - Choose one option from a list of options + +**Navigation and call to actions** + +- Menu - Action menus with optional nested submenus +- Tabs - Switch between related content panels +- Toolbar - Group related controls and actions + +**Content organization** + +- Accordion - Show and hide sections of content +- Tree - Display hierarchical data structures + Data display +- Grid - Navigate and interact with tabular data diff --git a/adev-ja/src/content/guide/aria/tabs.md b/adev-ja/src/content/guide/aria/tabs.md index d9f676714f..29a292c37b 100644 --- a/adev-ja/src/content/guide/aria/tabs.md +++ b/adev-ja/src/content/guide/aria/tabs.md @@ -1,23 +1,296 @@ - - - + + +## Overview - + + + + + + + -### Example with TailwindCSS + + + + + + + + - +## Usage + +Tabs work well for organizing related content into distinct sections where users switch between different views or categories. + +**Use tabs when:** + +- Organizing related content into distinct sections +- Creating settings panels with multiple categories +- Building documentation with multiple topics +- Implementing dashboards with different views +- Showing content where users need to switch contexts + +**Avoid tabs when:** + +- Building sequential forms or wizards (use a stepper pattern) +- Navigating between pages (use router navigation) +- Showing single content sections (no need for tabs) +- Having more than 7-8 tabs (consider a different layout) + +## Features + +- **Selection modes** - Tabs activate automatically on focus or require manual activation +- **Keyboard navigation** - Arrow keys, Home, and End for efficient tab navigation +- **Orientation** - Horizontal or vertical tab list layouts +- **Lazy content** - Tab panels render only when first activated +- **Disabled tabs** - Disable individual tabs with focus management +- **Focus modes** - Roving tabindex or activedescendant focus strategies +- **RTL support** - Right-to-left language navigation + +## Examples + +### Selection follows focus + +When selection follows focus, tabs activate immediately as you navigate with arrow keys. This provides instant feedback and works well for lightweight content. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Set `[selectionMode]="'follow'"` on the tab list to enable this behavior. + +### Manual activation + +With manual activation, arrow keys move focus between tabs without changing the selected tab. Users press Space or Enter to activate the focused tab. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Use `[selectionMode]="'explicit'"` for heavy content panels to avoid unnecessary rendering. + +### Vertical tabs + +Arrange tabs vertically for interfaces like settings panels or navigation sidebars. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Set `[orientation]="'vertical'"` on the tab list. Navigation changes to Up/Down arrow keys. + +### Lazy content rendering + +Use the `ngTabContent` directive on an `ng-template` to defer rendering tab panels until they're first shown. + +```angular-html +
+
    +
  • Tab 1
  • +
  • Tab 2
  • +
+ +
+ + + + +
+ +
+ + + + +
+
+``` + +By default, content remains in the DOM after the panel is hidden. Set `[preserveContent]="false"` to remove content when the panel is deactivated. + +### Disabled tabs + +Disable specific tabs to prevent user interaction. Control whether disabled tabs can receive keyboard focus. + + + + + + + + + + + + + + + + + + + + + + + + + + + +When `[softDisabled]="true"` on the tab list, disabled tabs can receive focus but cannot be activated. When `[softDisabled]="false"`, disabled tabs are skipped during keyboard navigation. + +## APIs + +### Tabs + +The container directive that coordinates tab lists and panels. + +This directive has no inputs or outputs. It serves as the root container for `ngTabList`, `ngTab`, and `ngTabPanel` directives. + +### TabList + +The container for tab buttons that manages selection and keyboard navigation. + +#### Inputs + +| Property | Type | Default | Description | +| --------------- | ---------------------------- | -------------- | ------------------------------------------------------------------ | +| `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` | Tab list layout direction | +| `wrap` | `boolean` | `false` | Whether keyboard navigation wraps from last to first tab | +| `softDisabled` | `boolean` | `true` | When `true`, disabled tabs are focusable but not activatable | +| `selectionMode` | `'follow' \| 'explicit'` | `'follow'` | Whether tabs activate on focus or require explicit activation | +| `selectedTab` | `any` | — | The value of the currently selected tab (supports two-way binding) | + +### Tab + +An individual tab button. + +#### Inputs + +| Property | Type | Default | Description | +| ---------- | --------- | ------- | --------------------------------------- | +| `value` | `any` | — | **Required.** Unique value for this tab | +| `disabled` | `boolean` | `false` | Disables this tab | + +#### Signals + +| Property | Type | Description | +| ---------- | ----------------- | ------------------------------------- | +| `selected` | `Signal` | Whether the tab is currently selected | +| `active` | `Signal` | Whether the tab currently has focus | + +### TabPanel + +The content panel associated with a tab. + +#### Inputs + +| Property | Type | Default | Description | +| ----------------- | --------- | ------- | ---------------------------------------------------------- | +| `value` | `any` | — | **Required.** Must match the `value` of the associated tab | +| `preserveContent` | `boolean` | `true` | Whether to keep panel content in DOM after deactivation | + +#### Signals + +| Property | Type | Description | +| --------- | ----------------- | -------------------------------------- | +| `visible` | `Signal` | Whether the panel is currently visible | + +### TabContent + +A structural directive for lazy rendering tab panel content. + +This directive has no inputs, outputs, or methods. Apply it to an `ng-template` element inside a tab panel: + +```angular-html +
+ + + +
+``` diff --git a/adev-ja/src/content/guide/aria/toolbar.md b/adev-ja/src/content/guide/aria/toolbar.md index 9fd328563a..1684759c0c 100644 --- a/adev-ja/src/content/guide/aria/toolbar.md +++ b/adev-ja/src/content/guide/aria/toolbar.md @@ -1,23 +1,272 @@ - - - - - +## Overview + +A container for grouping related controls and actions with keyboard navigation, commonly used for text formatting, toolbars, and command panels. + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Usage + +Toolbar works best for grouping related controls that users access frequently. Consider using toolbar when: + +- **Multiple related actions** - You have several controls that perform related functions (like text formatting buttons) +- **Keyboard efficiency matters** - Users benefit from quick keyboard navigation through arrow keys +- **Grouped controls** - You need to organize controls into logical sections with separators +- **Frequent access** - Controls are used repeatedly within a workflow + +Avoid toolbar when: + +- A simple button group is sufficient - For just 2-3 unrelated actions, individual buttons work better +- Controls aren't related - Toolbar implies a logical grouping; unrelated controls confuse users +- Complex nested navigation - Deep hierarchies are better served by menus or navigation components + +## Features + +Angular's toolbar provides a fully accessible toolbar implementation with: + +- **Keyboard Navigation** - Navigate widgets with arrow keys, activate with Enter or Space +- **Screen Reader Support** - Built-in ARIA attributes for assistive technologies +- **Widget Groups** - Organize related widgets like radio button groups or toggle button groups +- **Flexible Orientation** - Horizontal or vertical layouts with automatic keyboard navigation +- **Signal-Based Reactivity** - Reactive state management using Angular signals +- **Bidirectional Text Support** - Automatically handles right-to-left (RTL) languages +- **Configurable Focus** - Choose between wrapping navigation or hard stops at edges + +## Examples + +### Basic horizontal toolbar + +Horizontal toolbars organize controls from left to right, matching the common pattern in text editors and design tools. Arrow keys navigate between widgets, maintaining focus within the toolbar until users press Tab to move to the next page element. + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Vertical toolbar + +Vertical toolbars stack controls top to bottom, useful for side panels or vertical command palettes. Up and down arrow keys navigate between widgets. + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Widget groups + +Widget groups contain related controls that work together, like text alignment options or list formatting choices. Groups maintain their own internal state while participating in toolbar navigation. + +In the examples above, the alignment buttons are wrapped in `ngToolbarWidgetGroup` with `role="radiogroup"` to create a mutually exclusive selection group. + +The `multi` input controls whether multiple widgets within a group can be selected simultaneously: + + +
+ + + +
- +
+ + + +
+
- - - - - +### Disabled widgets ---> +Toolbars support two disabled modes: -### Example with TailwindCSS +1. **Soft-disabled** widgets remain focusable but visually indicate they're unavailable +2. **Hard-disabled** widgets are completely removed from keyboard navigation. - +By default, `softDisabled` is `true`, which allows disabled widgets to still receive focus. If you want to enable hard-disabled mode, set `[softDisabled]="false"` on the toolbar. + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Right-to-left (RTL) support + +Toolbars automatically support right-to-left languages. Wrap the toolbar in a container with `dir="rtl"` to reverse the layout and keyboard navigation direction. Arrow key navigation adjusts automatically: left arrow moves to the next widget, right arrow to the previous. + + + + + + + + + + + + + + + + + + + + + + + + + + + +## APIs + +### Toolbar Directive + +The `ngToolbar` directive provides the container for toolbar functionality. + +#### Inputs + +| Property | Type | Default | Description | +| -------------- | ------------------------------ | -------------- | ------------------------------------------------------ | +| `orientation` | `'vertical'` \| `'horizontal'` | `'horizontal'` | Whether toolbar is vertically or horizontally oriented | +| `disabled` | `boolean` | `false` | Disables the entire toolbar | +| `softDisabled` | `boolean` | `true` | Whether disabled items can receive focus | +| `wrap` | `boolean` | `true` | Whether focus should wrap at the edges | + +### ToolbarWidget Directive + +The `ngToolbarWidget` directive marks an element as a navigable widget within the toolbar. + +#### Inputs + +| Property | Type | Default | Description | +| ---------- | --------- | ------- | ----------------------------------------------- | +| `id` | `string` | auto | Unique identifier for the widget | +| `disabled` | `boolean` | `false` | Disables the widget | +| `value` | `V` | - | The value associated with the widget (required) | + +#### Signals + +| Property | Type | Description | +| ---------- | ----------------- | ------------------------------------------- | +| `active` | `Signal` | Whether the widget is currently focused | +| `selected` | `Signal` | Whether the widget is selected (in a group) | + +### ToolbarWidgetGroup Directive + +The `ngToolbarWidgetGroup` directive groups related widgets together. + +#### Inputs + +| Property | Type | Default | Description | +| ---------- | --------- | ------- | ---------------------------------------- | +| `disabled` | `boolean` | `false` | Disables all widgets in the group | +| `multi` | `boolean` | `false` | Whether multiple widgets can be selected | + +### Related components + +Toolbar can contain various widget types including buttons, trees, and comboboxes. See individual component documentation for specific widget implementations. + + + + + diff --git a/adev-ja/src/content/guide/aria/tree.md b/adev-ja/src/content/guide/aria/tree.md index f3c1fc81d1..4119a887d4 100644 --- a/adev-ja/src/content/guide/aria/tree.md +++ b/adev-ja/src/content/guide/aria/tree.md @@ -1,23 +1,230 @@ - - - + + +## Overview - +## Usage -### Example with TailwindCSS +Trees work well for displaying hierarchical data where users need to navigate through nested structures. - +**Use trees when:** + +- Building file system navigation +- Showing folder and document hierarchies +- Creating nested menu structures +- Displaying organization charts +- Browsing hierarchical data +- Implementing site navigation with nested sections + +**Avoid trees when:** + +- Displaying flat lists (use [Listbox](guide/aria/listbox) instead) +- Showing data tables (use [Grid](guide/aria/grid) instead) +- Creating simple dropdowns (use [Select](guide/aria/select) instead) +- Building breadcrumb navigation (use breadcrumb patterns) + +## Features + +- **Hierarchical navigation** - Nested tree structure with expand and collapse functionality +- **Selection modes** - Single or multi-selection with explicit or follow-focus behavior +- **Selection follows focus** - Optional automatic selection when focus changes +- **Keyboard navigation** - Arrow keys, Home, End, and type-ahead search +- **Expand/collapse** - Right/Left arrows or Enter to toggle parent nodes +- **Disabled items** - Disable specific nodes with focus management +- **Focus modes** - Roving tabindex or activedescendant focus strategies +- **RTL support** - Right-to-left language navigation + +## Examples + +### Navigation tree + +Use a tree for navigation where clicking items triggers actions rather than selecting them. + + + + + + + + + + + +Set `[nav]="true"` to enable navigation mode. This uses `aria-current` to indicate the current page instead of selection. + +### Single selection + +Enable single selection for scenarios where users choose one item from the tree. + + + + + + + + + + + + + + + + + + +Leave `[multi]="false"` (the default) for single selection. Users press Space to select the focused item. + +### Multi-selection + +Allow users to select multiple items from the tree. + + + + + + + + + + + + + + + + + + +Set `[multi]="true"` on the tree. Users select items individually with Space or select ranges with Shift+Arrow keys. + +### Selection follows focus + +When selection follows focus, the focused item is automatically selected. This simplifies interaction for navigation scenarios. + + + + + + + + + + + + + + + + + + +Set `[selectionMode]="'follow'"` on the tree. Selection automatically updates as users navigate with arrow keys. + +### Disabled tree items + +Disable specific tree nodes to prevent interaction. Control whether disabled items can receive focus. + + + + + + + + + + + + + + + + + + +When `[softDisabled]="true"` on the tree, disabled items can receive focus but cannot be activated or selected. When `[softDisabled]="false"`, disabled items are skipped during keyboard navigation. + +## APIs + +### Tree + +The container directive that manages hierarchical navigation and selection. + +#### Inputs + +| Property | Type | Default | Description | +| --------------- | -------------------------------- | ------------ | ------------------------------------------------------------- | +| `disabled` | `boolean` | `false` | Disables the entire tree | +| `softDisabled` | `boolean` | `true` | When `true`, disabled items are focusable but not interactive | +| `multi` | `boolean` | `false` | Whether multiple items can be selected | +| `selectionMode` | `'explicit' \| 'follow'` | `'explicit'` | Whether selection requires explicit action or follows focus | +| `nav` | `boolean` | `false` | Whether the tree is in navigation mode (uses `aria-current`) | +| `wrap` | `boolean` | `true` | Whether keyboard navigation wraps from last to first item | +| `focusMode` | `'roving' \| 'activedescendant'` | `'roving'` | Focus strategy used by the tree | +| `values` | `any[]` | `[]` | Selected item values (supports two-way binding) | + +#### Methods + +| Method | Parameters | Description | +| ---------------- | ---------- | --------------------------------------------- | +| `expandAll` | none | Expands all tree nodes | +| `collapseAll` | none | Collapses all tree nodes | +| `selectAll` | none | Selects all items (only in multi-select mode) | +| `clearSelection` | none | Clears all selection | + +### TreeItem + +An individual node in the tree that can contain child nodes. + +#### Inputs + +| Property | Type | Default | Description | +| ---------- | --------- | ------- | ------------------------------------------------------- | +| `value` | `any` | — | **Required.** Unique value for this tree item | +| `disabled` | `boolean` | `false` | Disables this item | +| `expanded` | `boolean` | `false` | Whether the node is expanded (supports two-way binding) | + +#### Signals + +| Property | Type | Description | +| ------------- | ----------------- | ------------------------------------ | +| `selected` | `Signal` | Whether the item is selected | +| `active` | `Signal` | Whether the item currently has focus | +| `hasChildren` | `Signal` | Whether the item has child nodes | + +#### Methods + +| Method | Parameters | Description | +| ---------- | ---------- | --------------------------- | +| `expand` | none | Expands this node | +| `collapse` | none | Collapses this node | +| `toggle` | none | Toggles the expansion state | + +### TreeGroup + +A container for child tree items. + +This directive has no inputs, outputs, or methods. It serves as a container to organize child `ngTreeItem` elements: + +```angular-html +
  • + Parent Item +
      +
    • Child 1
    • +
    • Child 2
    • +
    +
  • +``` diff --git a/adev-ja/src/content/guide/drag-drop.md b/adev-ja/src/content/guide/drag-drop.md index 50f89e3365..48a902b0ab 100644 --- a/adev-ja/src/content/guide/drag-drop.md +++ b/adev-ja/src/content/guide/drag-drop.md @@ -1,7 +1,9 @@ # Drag and drop ## Overview + This page describes the drag and drop directives which lets you quickly create drag and drop interfaces with the following: + - Free dragging - Create a list of reorderable draggable elements - Transfer draggable elements between lists @@ -19,38 +21,36 @@ For the full API reference, please see the [Angular CDK's drag and drop API refe The [Component Dev Kit (CDK)](https://material.angular.dev/cdk/categories) is a set of behavior primitives for building components. To use the drag and drop directives, first install `@angular/cdk` from npm. You can do this from your terminal using Angular CLI: - - ng add @angular/cdk - +```shell +ng add @angular/cdk +``` ### Importing drag and drop To use drag and drop, import what you need from the directives in your component. - +```ts import {Component} from '@angular/core'; import {CdkDrag} from '@angular/cdk/drag-drop'; @Component({ selector: 'my-custom-component', templateUrl: 'my-custom-component.html', - standalone: true, imports: [CdkDrag], }) export class DragDropExample {} - +``` ## Create draggable elements You can make any element draggable by adding the `cdkDrag` directive. By default, all draggable elements support free dragging. - - - + + + - ## Create a list of reorderable draggable elements Add the `cdkDropList` directive to a parent element to group draggable elements into a reorderable collection. This defines where draggable elements can be dropped. The draggable elements in the drop list group rearrange automatically as an element moves. @@ -58,9 +58,9 @@ Add the `cdkDropList` directive to a parent element to group draggable elements The drag and drop directives don't update your data model. To update the data model, listen to the `cdkDropListDropped` event (once the user finishes dragging) and update the data model manually. - - - + + + You can use the `CDK_DROP_LIST` injection token that can be used to reference instances of `cdkDropList`. For more information see the [dependency injection guide](https://angular.dev/guide/di) and the [drop list injection token API](api/cdk/drag-drop/CDK_DROP_LIST). @@ -68,6 +68,7 @@ You can use the `CDK_DROP_LIST` injection token that can be used to reference in ## Transfer draggable elements between lists The `cdkDropList` directive supports transferring draggable elements between connected drop lists. There are two ways to connect one or more `cdkDropList` instances together: + - Set the `cdkDropListConnectedTo` property to another drop list. - Wrap the elements in an element with the `cdkDropListGroup` attribute. @@ -84,9 +85,9 @@ The `cdkDropListConnectedTo` directive works both with a direct reference to ano - - - + + + Use the `cdkDropListGroup` directive if you have an unknown number of connected drop lists to set up the connection automatically. Any new `cdkDropList` that is added under a group automatically connects to all other lists. @@ -101,9 +102,9 @@ Use the `cdkDropListGroup` directive if you have an unknown number of connected - - - + + + You can use the `CDK_DROP_LIST_GROUP` injection token that can be used to reference instances of `cdkDropListGroup`. For more information see the [dependency injection guide](https://angular.dev/guide/di) and the [drop list group injection token API](api/cdk/drag-drop/CDK_DROP_LIST_GROUP). @@ -113,9 +114,9 @@ You can use the `CDK_DROP_LIST_GROUP` injection token that can be used to refere By default, a user can move `cdkDrag` elements from one container into another connected container. For more fine-grained control over which elements can be dropped into a container, use `cdkDropListEnterPredicate`. Angular calls the predicate whenever a draggable element enters a new container. Depending on whether the predicate returns true or false, the item may or may not be allowed into the new container. - - - + + + ## Attach data @@ -139,12 +140,11 @@ You can associate some arbitrary data with both `cdkDrag` and `cdkDropList` by s By default, the user can drag the entire `cdkDrag` element to move it around. To restrict the user to only be able to do so using a handle element, add the `cdkDragHandle` directive to an element inside of `cdkDrag`. You can have as many `cdkDragHandle` elements as you want. - - - + + + - You can use the `CDK_DRAG_HANDLE` injection token that can be used to reference instances of `cdkDragHandle`. For more information see the [dependency injection guide](https://angular.dev/guide/di) and the [drag handle injection token API](api/cdk/drag-drop/CDK_DRAG_HANDLE). ### Customize drag preview @@ -156,9 +156,9 @@ To customize the preview, provide a custom template via `*cdkDragPreview`. The c The cloned element removes its id attribute in order to avoid having multiple elements with the same id on the page. This will cause any CSS that targets that id not to be applied. - - - + + + You can use the `CDK_DRAG_PREVIEW` injection token that can be used to reference instances of `cdkDragPreview`. For more information see the [dependency injection guide](https://angular.dev/guide/di) and the [drag preview injection token API](api/cdk/drag-drop/CDK_DRAG_PREVIEW). @@ -169,11 +169,11 @@ By default, Angular inserts the `cdkDrag` preview into the `` of the page You can change where Angular inserts the preview using the `cdkDragPreviewContainer` input on `cdkDrag`. The possible values are: -| Value | Description | Advantages | Disadvantages | -|:--- |:--- |:--- |:--- | -| `global` | Default value. Angular inserts the preview into the or the closest shadow root. | Preview won't be affected by `z-index` or `overflow: hidden`. It also won't affect `:nth-child` selectors and flex layouts. | Doesn't retain inherited styles. | -| `parent` | Angular inserts the preview inside the parent of the element that is being dragged. | Preview inherits the same styles as the dragged element. | Preview may be clipped by `overflow: hidden` or be placed under other elements due to `z-index`. Furthermore, it can affect `:nth-child` selectors and some flex layouts. | -| `ElementRef` or `HTMLElement` | Angular inserts the preview into the specified element. | Preview inherits styles from the specified container element. | Preview may be clipped by `overflow: hidden` or be placed under other elements due to `z-index`. Furthermore, it can affect `:nth-child` selectors and some flex layouts. | +| Value | Description | Advantages | Disadvantages | +| :---------------------------- | :------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `global` | Default value. Angular inserts the preview into the or the closest shadow root. | Preview won't be affected by `z-index` or `overflow: hidden`. It also won't affect `:nth-child` selectors and flex layouts. | Doesn't retain inherited styles. | +| `parent` | Angular inserts the preview inside the parent of the element that is being dragged. | Preview inherits the same styles as the dragged element. | Preview may be clipped by `overflow: hidden` or be placed under other elements due to `z-index`. Furthermore, it can affect `:nth-child` selectors and some flex layouts. | +| `ElementRef` or `HTMLElement` | Angular inserts the preview into the specified element. | Preview inherits styles from the specified container element. | Preview may be clipped by `overflow: hidden` or be placed under other elements due to `z-index`. Furthermore, it can affect `:nth-child` selectors and some flex layouts. | Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `previewContainer` within the config if the value is `global` or `parent`. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). @@ -182,9 +182,9 @@ Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `p While a `cdkDrag` element is being dragged, the directive creates a placeholder element that shows where the element will be placed when dropped. By default, the placeholder is a clone of the element that is being dragged. You can replace the placeholder with a custom one using the `*cdkDragPlaceholder` directive: - - - + + + You can use the `CDK_DRAG_PLACEHOLDER` injection token that can be used to reference instances of `cdkDragPlaceholder`. For more information see the [dependency injection guide](https://angular.dev/guide/di) and the [drag placeholder injection token API](api/cdk/drag-drop/CDK_DRAG_PLACEHOLDER). @@ -196,9 +196,9 @@ Set the `cdkDragRootElement` attribute if there's an element that you want to ma The attribute accepts a selector and looks up the DOM until it finds an element that matches the selector. If an element is found, it becomes draggable. This is useful for cases such as making a dialog draggable. - - - + + + Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `rootElementSelector` within the config. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). @@ -208,9 +208,9 @@ Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `r By default, `cdkDrag` elements not in a `cdkDropList` move from their normal DOM position only when a user manually moves the element. Use the `cdkDragFreeDragPosition` input to explicitly set the element’s position. A common use case for this is restoring a draggable element's position after a user has navigated away and then returned. - - - + + + ### Restrict movement within an element @@ -218,9 +218,9 @@ By default, `cdkDrag` elements not in a `cdkDropList` move from their normal DOM To stop the user from being able to drag a `cdkDrag` element outside of another element, pass a CSS selector to the `cdkDragBoundary` attribute. This attribute accepts a selector and looks up the DOM until it finds an element that matches it. If a match is found, the element becomes the boundary that the draggable element can't be dragged outside of `cdkDragBoundary` can also be used when `cdkDrag` is placed inside a `cdkDropList`. - - - + + + Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update boundaryElement within the config. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). @@ -230,9 +230,9 @@ Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update bo By default, `cdkDrag` allows free movement in all directions. To restrict dragging to a specific axis, set `cdkDragLockAxis` to either "x" or "y"on `cdkDrag`. To restrict dragging for multiple draggable elements within `cdkDropList`, set `cdkDropListLockAxis` on `cdkDropList` instead. - - - + + + Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `lockAxis` within the config. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). @@ -244,9 +244,9 @@ By default when the user puts their pointer down on a `cdkDrag`, the dragging se You can delay the dragging sequence using the `cdkDragStartDelay` input. The input waits for the user to hold down their pointer for the specified number of milliseconds before dragging the element. - - - + + + Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update dragStartDelay within the config. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). @@ -256,12 +256,12 @@ Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update dr If you want to disable dragging for a particular drag item, set the `cdkDragDisabled` input on a `cdkDrag` item to true or false. You can disable an entire list using the `cdkDropListDisabled` input on a `cdkDropList`. It is also possible to disable a specific handle via `cdkDragHandleDisabled` on `cdkDragHandle`. - - - + + + -Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `draggingDisabled` within the config. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). +Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `draggingDisabled` within the config. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). ## Sorting customizations @@ -270,9 +270,9 @@ Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `d By default, the `cdkDropList` directive assumes lists are vertical. This can be changed by setting the `cdkDropListOrientation` property to horizontal. - - - + + + Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update `listOrientation` within the config. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). @@ -284,9 +284,9 @@ By default, the `cdkDropList` sorts the draggable elements by moving them around If you have a sortable list that needs to wrap onto new lines, you can set `cdkDropListOrientation` attribute to `mixed`. This causes the list to use a different strategy of sorting the elements which involves moving them in the DOM. However the list can no longer animate the sorting action . - - - + + + ### Selective sorting @@ -294,20 +294,19 @@ If you have a sortable list that needs to wrap onto new lines, you can set `cdkD By default, `cdkDrag` elements are sorted into any position inside of a `cdkDropList`. To change this behavior, set the `cdkDropListSortPredicate` attribute which takes in a function. The predicate function is called whenever a draggable element is about to be moved into a new index within the drop list. If the predicate returns true, the item will be moved into the new index, otherwise it will keep its current position. - - - + + + - ### Disable sorting There are cases where draggable elements can be dragged out of one `cdkDropList` into another, however the user shouldn't be able to sort them within the source list. For these cases, add the `cdkDropListSortingDisabled` attribute to prevent the draggable elements in a `cdkDropList` from sorting. This preserves the dragged element's initial position in the source list if it does not get dragged to a new valid position. - - - + + + Alternatively, you can modify the `CDK_DRAG_CONFIG` injection token to update sortingDisabled within the config. For more information see the [dependency injection guide](https://angular.dev/guide/di), [drag config injection token API](api/cdk/drag-drop/CDK_DRAG_CONFIG), and the [drag drop config API](api/cdk/drag-drop/DragDropConfig). @@ -321,41 +320,41 @@ To enable copying, you can set the `cdkDropListHasAnchor` input. This tells the Combining `cdkDropListHasAnchor` with `cdkDropListSortingDisabled` makes it possible to construct a list from which a user can copy items without being able to reorder the source list (e.g. a product list and a shopping cart). - - - + + + ## Customize animations Drag and drop supports animations for both: + - Sorting an draggable element inside a list - Moving the draggable element from the position that the user dropped it to the final position inside the list To set up your animations, define a CSS transition that targets the transform property. The following classes can be used for animations: -| CSS class name | Result of adding transition | -|:--- |:--- | -| .cdk-drag | Animate draggable elements as they are being sorted. | -| .cdk-drag-animating | Animate the draggable element from its dropped position to the final position within the `cdkDropList`.

    This CSS class is applied to a `cdkDrag` element only when the dragging action has stopped. | +| CSS class name | Result of adding transition | +| :------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| .cdk-drag | Animate draggable elements as they are being sorted. | +| .cdk-drag-animating | Animate the draggable element from its dropped position to the final position within the `cdkDropList`.

    This CSS class is applied to a `cdkDrag` element only when the dragging action has stopped. | ## Styling Both `cdkDrag` and `cdkDropList` directives only apply essential styles needed for functionality. Applications can customize their styles by targeting these specified CSS classes. - -| CSS class name | Description | -|:--- |:--- | -| .cdk-drop-list | Selector for the `cdkDropList` container elements. | -| .cdk-drag | Selector for `cdkDrag` elements. | -| .cdk-drag-disabled | Selector for disabled `cdkDrag` elements. | -| .cdk-drag-handle | Selector for the host element of the `cdkDragHandle`. | -| .cdk-drag-preview | Selector for the drag preview element. This is the element that appears next to the cursor as a user drags an element in a sortable list.

    The element looks exactly like the element that is being dragged unless customized with a custom template through `*cdkDragPreview`. | -| .cdk-drag-placeholder | Selector for the drag placeholder element. This is the element that is shown in the spot where the draggable element will be dragged to once the dragging action ends.

    This element looks exactly like the element that is being sorted unless customized with the cdkDragPlaceholder directive. | -| .cdk-drop-list-dragging | Selector for `cdkDropList` container element that has a draggable element currently being dragged. | -| .cdk-drop-list-disabled | Selector for `cdkDropList` container elements that are disabled. | -| .cdk-drop-list-receiving | Selector for `cdkDropList` container element that has a draggable element it can receive from a connected drop list that is currently being dragged. | -| .cdk-drag-anchor | Selector for the anchor element that is created when `cdkDropListHasAnchor` is enabled. This element indicates the position from which the dragged item started. | +| CSS class name | Description | +| :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| .cdk-drop-list | Selector for the `cdkDropList` container elements. | +| .cdk-drag | Selector for `cdkDrag` elements. | +| .cdk-drag-disabled | Selector for disabled `cdkDrag` elements. | +| .cdk-drag-handle | Selector for the host element of the `cdkDragHandle`. | +| .cdk-drag-preview | Selector for the drag preview element. This is the element that appears next to the cursor as a user drags an element in a sortable list.

    The element looks exactly like the element that is being dragged unless customized with a custom template through `*cdkDragPreview`. | +| .cdk-drag-placeholder | Selector for the drag placeholder element. This is the element that is shown in the spot where the draggable element will be dragged to once the dragging action ends.

    This element looks exactly like the element that is being sorted unless customized with the cdkDragPlaceholder directive. | +| .cdk-drop-list-dragging | Selector for `cdkDropList` container element that has a draggable element currently being dragged. | +| .cdk-drop-list-disabled | Selector for `cdkDropList` container elements that are disabled. | +| .cdk-drop-list-receiving | Selector for `cdkDropList` container element that has a draggable element it can receive from a connected drop list that is currently being dragged. | +| .cdk-drag-anchor | Selector for the anchor element that is created when `cdkDropListHasAnchor` is enabled. This element indicates the position from which the dragged item started. | ## Dragging in a scrollable container diff --git a/adev-ja/src/content/guide/http/http-resource.md b/adev-ja/src/content/guide/http/http-resource.md index 4a0844bc90..c7c9467f46 100644 --- a/adev-ja/src/content/guide/http/http-resource.md +++ b/adev-ja/src/content/guide/http/http-resource.md @@ -8,10 +8,9 @@ For more about Angular's `resource` pattern, see [Async reactivity with `resourc ## `Using httpResource` -TIP: Make sure to include `provideHttpClient` in your application providers. See [Setting up HttpClient](/guide/http/setup) for details. +TIP: Make sure to include `provideHttpClient` in your application providers. See [Setting up HttpClient](/guide/http/setup) for details. - -You can define an HTTP resource by returning a url: +You can define an HTTP resource by returning a url: ```ts userId = input.required(); @@ -19,8 +18,8 @@ userId = input.required(); user = httpResource(() => `/api/user/${userId()}`); // A reactive function as argument ``` -`httpResource` is reactive, meaning that whenever one of the signal it depends on changes (like `userId`), the resource will emit a new http request. -If a request is already pending, the resource cancels the outstanding request before issuing a new one. +`httpResource` is reactive, meaning that whenever one of the signal it depends on changes (like `userId`), the resource will emit a new http request. +If a request is already pending, the resource cancels the outstanding request before issuing a new one. HELPFUL: `httpResource` differs from the `HttpClient` as it initiates the request _eagerly_. In contrast, the `HttpClient` only initiates requests upon subscription to the returned `Observable`. @@ -39,20 +38,21 @@ user = httpResource(() => ({ }, reportProgress: true, transferCache: true, - keepalive: true, - mode: 'cors', + keepalive: true, + mode: 'cors', redirect: 'error', priority: 'high', cache : 'force-cache', credentials: 'include', referrer: 'no-referrer', - integrity: 'sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GhEXAMPLEKEY=' + integrity: 'sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GhEXAMPLEKEY=', + referrerPolicy: 'no-referrer' })); ``` TIP: Avoid using `httpResource` for _mutations_ like `POST` or `PUT`. Instead, prefer directly using the underlying `HttpClient` APIs. -The signals of the `httpResource` can be used in the template to control which elements should be displayed. +The signals of the `httpResource` can be used in the template to control which elements should be displayed. ```angular-html @if(user.hasValue()) { @@ -66,9 +66,9 @@ The signals of the `httpResource` can be used in the template to control which e HELPFUL: Reading the `value` signal on a `resource` that is in error state throws at runtime. It is recommended to guard `value` reads with `hasValue()`. -### Response types +### Response types -By default, `httpResource` returns and parses the response as JSON. However, you can specify alternate return with additional functions on `httpResource`: +By default, `httpResource` returns and parses the response as JSON. However, you can specify alternate return with additional functions on `httpResource`: ```ts httpResource.text(() => ({ 
 })); // returns a string in value() diff --git a/adev-ja/src/content/guide/i18n/add-package.md b/adev-ja/src/content/guide/i18n/add-package.md index 325c565b4a..b273c8b117 100644 --- a/adev-ja/src/content/guide/i18n/add-package.md +++ b/adev-ja/src/content/guide/i18n/add-package.md @@ -15,10 +15,10 @@ If `@angular/localize` is not installed and you try to build a localized version ## Options -| OPTION | DESCRIPTION | VALUE TYPE | DEFAULT VALUE -|:--- |:--- |:------ |:------ -| `--project` | The name of the project. | `string` | -| `--use-at-runtime` | If set, then `$localize` can be used at runtime. Also `@angular/localize` gets included in the `dependencies` section of `package.json`, rather than `devDependencies`, which is the default. | `boolean` | `false` +| OPTION | DESCRIPTION | VALUE TYPE | DEFAULT VALUE | +| :----------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------- | :------------ | +| `--project` | The name of the project. | `string` | +| `--use-at-runtime` | If set, then `$localize` can be used at runtime. Also `@angular/localize` gets included in the `dependencies` section of `package.json`, rather than `devDependencies`, which is the default. | `boolean` | `false` | For more available options, see `ng add` in [Angular CLI][CliMain]. @@ -28,8 +28,6 @@ For more available options, see `ng add` in [Angular CLI][CliMain]. -[CliMain]: cli "CLI Overview and Command Reference | Angular" - -[GuideNpmPackages]: reference/configs/npm-packages "Workspace npm dependencies | Angular" - -[GuideTsConfig]: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html "TypeScript Configuration" +[CliMain]: cli 'CLI Overview and Command Reference | Angular' +[GuideNpmPackages]: reference/configs/npm-packages 'Workspace npm dependencies | Angular' +[GuideTsConfig]: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html 'TypeScript Configuration' diff --git a/adev-ja/src/content/guide/i18n/deploy.md b/adev-ja/src/content/guide/i18n/deploy.md index 9cb41acdc8..24a393e4c3 100644 --- a/adev-ja/src/content/guide/i18n/deploy.md +++ b/adev-ja/src/content/guide/i18n/deploy.md @@ -35,8 +35,6 @@ The following example displays an Apache configuration. -[CliBuild]: cli/build "ng build | CLI | Angular" - -[GuideDeployment]: tools/cli/deployment "Deployment | Angular" - -[GuideWorkspaceConfig]: reference/configs/workspace-config "Angular workspace configuration | Angular" +[CliBuild]: cli/build 'ng build | CLI | Angular' +[GuideDeployment]: tools/cli/deployment 'Deployment | Angular' +[GuideWorkspaceConfig]: reference/configs/workspace-config 'Angular workspace configuration | Angular' diff --git a/adev-ja/src/content/guide/i18n/example.md b/adev-ja/src/content/guide/i18n/example.md index 1825b49b3c..f7ce49d239 100644 --- a/adev-ja/src/content/guide/i18n/example.md +++ b/adev-ja/src/content/guide/i18n/example.md @@ -11,8 +11,8 @@ The following tabs display the example application and the associated translation files. - - + + diff --git a/adev-ja/src/content/guide/i18n/format-data-locale.md b/adev-ja/src/content/guide/i18n/format-data-locale.md index 016ae5c314..2e70eb9c70 100644 --- a/adev-ja/src/content/guide/i18n/format-data-locale.md +++ b/adev-ja/src/content/guide/i18n/format-data-locale.md @@ -3,8 +3,8 @@ Angular provides the following built-in data transformation [pipes](guide/templates/pipes). The data transformation pipes use the [`LOCALE_ID`][ApiCoreLocaleId] token to format data based on rules of each locale. -| Data transformation pipe | Details | -|:--- |:--- | +| Data transformation pipe | Details | +| :-------------------------------------- | :------------------------------------------------ | | [`DatePipe`][ApiCommonDatepipe] | Formats a date value. | | [`CurrencyPipe`][ApiCommonCurrencypipe] | Transforms a number into a currency string. | | [`DecimalPipe`][ApiCommonDecimalpipe] | Transforms a number into a decimal number string. | @@ -44,9 +44,8 @@ HELPFUL: The locale specified for the `CurrencyPipe` overrides the global `LOCAL -[ApiCommonCurrencypipe]: api/common/CurrencyPipe "CurrencyPipe | Common - API | Angular" - -[ApiCommonDatepipe]: api/common/DatePipe "DatePipe | Common - API | Angular" -[ApiCommonDecimalpipe]: api/common/DecimalPipe "DecimalPipe | Common - API | Angular" -[ApiCommonPercentpipe]: api/common/PercentPipe "PercentPipe | Common - API | Angular" -[ApiCoreLocaleId]: api/core/LOCALE_ID "LOCALE_ID | Core - API | Angular" +[ApiCommonCurrencypipe]: api/common/CurrencyPipe 'CurrencyPipe | Common - API | Angular' +[ApiCommonDatepipe]: api/common/DatePipe 'DatePipe | Common - API | Angular' +[ApiCommonDecimalpipe]: api/common/DecimalPipe 'DecimalPipe | Common - API | Angular' +[ApiCommonPercentpipe]: api/common/PercentPipe 'PercentPipe | Common - API | Angular' +[ApiCoreLocaleId]: api/core/LOCALE_ID 'LOCALE_ID | Core - API | Angular' diff --git a/adev-ja/src/content/guide/i18n/import-global-variants.md b/adev-ja/src/content/guide/i18n/import-global-variants.md index e9ad9b24cb..16ca839d62 100644 --- a/adev-ja/src/content/guide/i18n/import-global-variants.md +++ b/adev-ja/src/content/guide/i18n/import-global-variants.md @@ -4,11 +4,9 @@ The [Angular CLI][CliMain] automatically includes locale data if you run the [`n - - +```shell ng build --localize - - +``` HELPFUL: The initial installation of Angular already contains locale data for English in the United States \(`en-US`\). The [Angular CLI][CliMain] automatically includes the locale data and sets the `LOCALE_ID` value when you use the `--localize` option with [`ng build`][CliBuild] command. @@ -24,5 +22,5 @@ For example, you could import the global variants for French \(`fr`\) in `main.t HELPFUL: In an `NgModules` application, you would import it in your `app.module`. -[CliMain]: cli "CLI Overview and Command Reference | Angular" -[CliBuild]: cli/build "ng build | CLI | Angular" +[CliMain]: cli 'CLI Overview and Command Reference | Angular' +[CliBuild]: cli/build 'ng build | CLI | Angular' diff --git a/adev-ja/src/content/guide/i18n/locale-id.md b/adev-ja/src/content/guide/i18n/locale-id.md index 949dd97459..929df60486 100644 --- a/adev-ja/src/content/guide/i18n/locale-id.md +++ b/adev-ja/src/content/guide/i18n/locale-id.md @@ -1,13 +1,13 @@ # Refer to locales by ID -Angular uses the Unicode *locale identifier* \(Unicode locale ID\) to find the correct locale data for internationalization of text strings. +Angular uses the Unicode _locale identifier_ \(Unicode locale ID\) to find the correct locale data for internationalization of text strings. -* A locale ID conforms to the [Unicode Common Locale Data Repository (CLDR) core specification][UnicodeCldrDevelopmentCoreSpecification]. - For more information about locale IDs, see [Unicode Language and Locale Identifiers][UnicodeCldrDevelopmentCoreSpecificationLocaleIDs]. +- A locale ID conforms to the [Unicode Common Locale Data Repository (CLDR) core specification][UnicodeCldrDevelopmentCoreSpecification]. + For more information about locale IDs, see [Unicode Language and Locale Identifiers][UnicodeCldrDevelopmentCoreSpecificationLocaleIDs]. -* CLDR and Angular use [BCP 47 tags][RfcEditorInfoBcp47] as the base for the locale ID +- CLDR and Angular use [BCP 47 tags][RfcEditorInfoBcp47] as the base for the locale ID @@ -26,7 +26,7 @@ The differences include grammar, punctuation, formats for currency, decimal numb For the examples in this guide, use the following languages and locales. | Language | Locale | Unicode locale ID | -|:--- |:--- |:--- | +| :------- | :----------------------- | :---------------- | | English | Canada | `en-CA` | | English | United States of America | `en-US` | | French | Canada | `fr-CA` | @@ -48,6 +48,7 @@ To change the source locale of your project for the build, complete the followin 1. Open the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file. 2. Add or modify the `sourceLocale` field inside the `i18n` section: + ```json { "projects": { @@ -66,12 +67,8 @@ To change the source locale of your project for the build, complete the followin -[GuideWorkspaceConfig]: reference/configs/workspace-config "Angular workspace configuration | Angular" - -[GithubAngularAngularTreeMasterPackagesCommonLocales]: "angular/packages/common/locales | angular/angular | GitHub" - -[RfcEditorInfoBcp47]: https://www.rfc-editor.org/info/bcp47 "BCP 47 | RFC Editor" - -[UnicodeCldrDevelopmentCoreSpecification]: https://cldr.unicode.org/index/cldr-spec "Core Specification | Unicode CLDR Project" - -[UnicodeCldrDevelopmentCoreSpecificationLocaleID]: https://cldr.unicode.org/index/cldr-spec/picking-the-right-language-code "Unicode Language and Locale Identifiers - Core Specification | Unicode CLDR Project" +[GuideWorkspaceConfig]: reference/configs/workspace-config 'Angular workspace configuration | Angular' +[GithubAngularAngularTreeMasterPackagesCommonLocales]: https://github.com/angular/angular/tree/main/packages/common/locales 'angular/packages/common/locales | angular/angular | GitHub' +[RfcEditorInfoBcp47]: https://www.rfc-editor.org/info/bcp47 'BCP 47 | RFC Editor' +[UnicodeCldrDevelopmentCoreSpecification]: https://cldr.unicode.org/index/cldr-spec 'Core Specification | Unicode CLDR Project' +[UnicodeCldrDevelopmentCoreSpecificationLocaleID]: https://cldr.unicode.org/index/cldr-spec/picking-the-right-language-code 'Unicode Language and Locale Identifiers - Core Specification | Unicode CLDR Project' diff --git a/adev-ja/src/content/guide/i18n/manage-marked-text.md b/adev-ja/src/content/guide/i18n/manage-marked-text.md index 69a11047ce..5735ae5ed7 100644 --- a/adev-ja/src/content/guide/i18n/manage-marked-text.md +++ b/adev-ja/src/content/guide/i18n/manage-marked-text.md @@ -2,8 +2,8 @@ The Angular extractor generates a file with a translation unit entry each of the following instances. -* Each `i18n` attribute in a component template -* Each [`$localize`][ApiLocalizeInitLocalize] tagged message string in component code +- Each `i18n` attribute in a component template +- Each [`$localize`][ApiLocalizeInitLocalize] tagged message string in component code As described in [How meanings control text extraction and merges][GuideI18nCommonPrepareHowMeaningsControlTextExtractionAndMerges], Angular assigns each translation unit a unique ID. @@ -24,7 +24,7 @@ Additional metadata may include the library, component, or area of the applicati To specify a custom ID in the `i18n` attribute or [`$localize`][ApiLocalizeInitLocalize] tagged message string, use the `@@` prefix. The following example defines the `introductionHeader` custom ID in a heading element. - + The following example defines the `introductionHeader` custom ID for a variable. @@ -50,7 +50,7 @@ Use a custom ID in combination with a description and a meaning to further help The following example includes a description, followed by the custom ID. - + The following example defines the `introductionHeader` custom ID and description for a variable. @@ -64,7 +64,7 @@ variableText2 = $localize`:An introduction header for this sample@@introductionH The following example adds a meaning. - + The following example defines the `introductionHeader` custom ID for a variable. @@ -83,7 +83,7 @@ If you use the same ID for two different text elements, the extraction tool extr For example, in the following code snippet the same `myId` custom ID is defined for two different text elements. - + The following displays the translation in French. @@ -93,6 +93,5 @@ Both elements now use the same translation \(`Bonjour`\), because both were defi -[ApiLocalizeInitLocalize]: api/localize/init/$localize "$localize | init - localize - API | Angular" - -[GuideI18nCommonPrepareHowMeaningsControlTextExtractionAndMerges]: guide/i18n/prepare#h1-example "How meanings control text extraction and merges - Prepare components for translations | Angular" +[ApiLocalizeInitLocalize]: api/localize/init/$localize '$localize | init - localize - API | Angular' +[GuideI18nCommonPrepareHowMeaningsControlTextExtractionAndMerges]: guide/i18n/prepare#h1-example 'How meanings control text extraction and merges - Prepare components for translations | Angular' diff --git a/adev-ja/src/content/guide/i18n/merge.md b/adev-ja/src/content/guide/i18n/merge.md index 55a58ebbed..4b32a91eac 100644 --- a/adev-ja/src/content/guide/i18n/merge.md +++ b/adev-ja/src/content/guide/i18n/merge.md @@ -4,7 +4,7 @@ To merge the completed translations into your project, complete the following ac 1. Use the [Angular CLI][CliMain] to build a copy of the distributable files of your project 1. Use the `"localize"` option to replace all of the i18n messages with the valid translations and build a localized variant application. - A variant application is a complete copy of the distributable files of your application translated for a single locale. + A variant application is a complete copy of the distributable files of your application translated for a single locale. After you merge the translations, serve each distributable copy of the application using server-side language detection or different subdirectories. @@ -31,8 +31,8 @@ Use the `i18n` project option in the [`angular.json`][GuideWorkspaceConfig] work The following sub-options identify the source language and tell the compiler where to find supported translations for the project. -| Suboption | Details | -|:--- |:--- | +| Suboption | Details | +| :------------- | :--------------------------------------------------------------------------- | | `sourceLocale` | The locale you use within the application source code \(`en-US` by default\) | | `locales` | A map of locale identifiers to translation files | @@ -46,9 +46,9 @@ For example, the following excerpt of an [`angular.json`][GuideWorkspaceConfig] To use your locale definition in the build configuration, use the `"localize"` option in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file to tell the CLI which locales to generate for the build configuration. -* Set `"localize"` to `true` for all the locales previously defined in the build configuration. -* Set `"localize"` to an array of a subset of the previously defined locale identifiers to build only those locale versions. -* Set `"localize"` to `false` to disable localization and not generate any locale-specific versions. +- Set `"localize"` to `true` for all the locales previously defined in the build configuration. +- Set `"localize"` to an array of a subset of the previously defined locale identifiers to build only those locale versions. +- Set `"localize"` to `false` to disable localization and not generate any locale-specific versions. HELPFUL: Ahead-of-time (AOT) compilation is required to localize component templates. @@ -110,8 +110,8 @@ For production builds, use configuration composition to run both configurations. When a translation is missing, the build succeeds but generates a warning such as `Missing translation for message "{translation_text}"`. To configure the level of warning that is generated by the Angular compiler, specify one of the following levels. -| Warning level | Details | Output | -|:--- |:--- |:--- | +| Warning level | Details | Output | +| :------------ | :--------------------------------------------------- | :----------------------------------------------------- | | `error` | Throw an error and the build fails | n/a | | `ignore` | Do nothing | n/a | | `warning` | Displays the default warning in the console or shell | `Missing translation for message "{translation_text}"` | @@ -128,7 +128,7 @@ HELPFUL: When you compile your Angular project into an Angular application, the This means that your Angular application is translated after compilation. This also means that you can create localized versions of your Angular application without re-compiling your entire Angular project for each locale. -When you translate your Angular application, the *translation transformation* replaces and reorders the parts \(static strings and expressions\) of the template literal string with strings from a collection of translations. +When you translate your Angular application, the _translation transformation_ replaces and reorders the parts \(static strings and expressions\) of the template literal string with strings from a collection of translations. For more information, see [`$localize`][ApiLocalizeInitLocalize]. TLDR: Compile once, then translate for each locale. @@ -139,18 +139,13 @@ TLDR: Compile once, then translate for each locale. -[ApiLocalizeInitLocalize]: api/localize/init/$localize "$localize | init - localize - API | Angular" - -[CliMain]: cli "CLI Overview and Command Reference | Angular" -[CliBuild]: cli/build "ng build | CLI | Angular" - -[GuideBuild]: tools/cli/build "Building and serving Angular apps | Angular" - -[GuideI18nCommonMergeApplySpecificBuildOptionsForJustOneLocale]: guide/i18n/merge#apply-specific-build-options-for-just-one-locale "Apply specific build options for just one locale - Merge translations into the application | Angular" -[GuideI18nCommonMergeBuildFromTheCommandLine]: guide/i18n/merge#build-from-the-command-line "Build from the command line - Merge translations into the application | Angular" -[GuideI18nCommonMergeDefineLocalesInTheBuildConfiguration]: guide/i18n/merge#define-locales-in-the-build-configuration "Define locales in the build configuration - Merge translations into the application | Angular" -[GuideI18nCommonMergeGenerateApplicationVariantsForEachLocale]: guide/i18n/merge#generate-application-variants-for-each-locale "Generate application variants for each locale - Merge translations into the application | Angular" - -[GuideI18nCommonTranslationFilesChangeTheSourceLanguageFileFormat]: guide/i18n/translation-files#change-the-source-language-file-format "Change the source language file format - Work with translation files | Angular" - -[GuideWorkspaceConfig]: reference/configs/workspace-config "Angular workspace configuration | Angular" +[ApiLocalizeInitLocalize]: api/localize/init/$localize '$localize | init - localize - API | Angular' +[CliMain]: cli 'CLI Overview and Command Reference | Angular' +[CliBuild]: cli/build 'ng build | CLI | Angular' +[GuideBuild]: tools/cli/build 'Building and serving Angular apps | Angular' +[GuideI18nCommonMergeApplySpecificBuildOptionsForJustOneLocale]: guide/i18n/merge#apply-specific-build-options-for-just-one-locale 'Apply specific build options for just one locale - Merge translations into the application | Angular' +[GuideI18nCommonMergeBuildFromTheCommandLine]: guide/i18n/merge#build-from-the-command-line 'Build from the command line - Merge translations into the application | Angular' +[GuideI18nCommonMergeDefineLocalesInTheBuildConfiguration]: guide/i18n/merge#define-locales-in-the-build-configuration 'Define locales in the build configuration - Merge translations into the application | Angular' +[GuideI18nCommonMergeGenerateApplicationVariantsForEachLocale]: guide/i18n/merge#generate-application-variants-for-each-locale 'Generate application variants for each locale - Merge translations into the application | Angular' +[GuideI18nCommonTranslationFilesChangeTheSourceLanguageFileFormat]: guide/i18n/translation-files#change-the-source-language-file-format 'Change the source language file format - Work with translation files | Angular' +[GuideWorkspaceConfig]: reference/configs/workspace-config 'Angular workspace configuration | Angular' diff --git a/adev-ja/src/content/guide/i18n/overview.md b/adev-ja/src/content/guide/i18n/overview.md index d504e1aadf..5b2a7adc42 100644 --- a/adev-ja/src/content/guide/i18n/overview.md +++ b/adev-ja/src/content/guide/i18n/overview.md @@ -1,18 +1,18 @@ # Angular Internationalization (i18n) -*Internationalization*, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. -*Localization* is the process of building versions of your project for different locales. +_Internationalization_, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. +_Localization_ is the process of building versions of your project for different locales. The localization process includes the following actions. -* Extract text for translation into different languages -* Format data for a specific locale +- Extract text for translation into different languages +- Format data for a specific locale -A *locale* identifies a region in which people speak a particular language or language variant. +A _locale_ identifies a region in which people speak a particular language or language variant. Possible regions include countries and geographical regions. A locale determines the formatting and parsing of the following details. -* Measurement units including date and time, numbers, and currencies -* Translated names including time zones, languages, and countries +- Measurement units including date and time, numbers, and currencies +- Translated names including time zones, languages, and countries For a quick introduction to localization and internationalization watch this video: diff --git a/adev-ja/src/content/guide/i18n/prepare.md b/adev-ja/src/content/guide/i18n/prepare.md index 88482a6ad4..9031c486ea 100644 --- a/adev-ja/src/content/guide/i18n/prepare.md +++ b/adev-ja/src/content/guide/i18n/prepare.md @@ -23,20 +23,19 @@ HELPFUL: The `i18n` attribute is a custom attribute that the Angular tools and c The following `

    ` tag displays a simple English language greeting, "Hello i18n!". - + To mark the greeting for translation, add the `i18n` attribute to the `

    ` tag. - - + ### using conditional statement with `i18n` The following `
    ` tag will display translated text as part of `div` and `aria-label` based on toggle status - - + + ### Translate inline text without HTML element @@ -73,7 +72,7 @@ i18n-{attribute_name}="{meaning}|{description}@@{id}" To translate the title of an image, review this example. The following example displays an image with a `title` attribute. - + To mark the title attribute for translation, complete the following action. @@ -81,7 +80,7 @@ To mark the title attribute for translation, complete the following action. The following example displays how to mark the `title` attribute on the `img` tag by adding `i18n-title`. - + ## Mark text in component code @@ -125,8 +124,6 @@ $localize`string_to_translate ${variable_name}:placeholder_name:`; return this.show ? $localize`Show Tabs` : $localize`Hide tabs`; - - ## i18n metadata for translation @@ -153,7 +150,7 @@ Add a _description_ of the text message as the value of the `i18n` attribute or The following example shows the value of the `i18n` attribute. - + The following example shows the value of the [`$localize`][ApiLocalizeInitLocalize] tagged message string with a description. @@ -174,7 +171,7 @@ For example, you may want to specify that the `

    ` tag is a site header that y The following example shows how to specify that the `

    ` tag must be translated as a header or referenced elsewhere. - + The result is any text marked with `site header`, as the _meaning_ is translated exactly the same way. @@ -329,7 +326,7 @@ updated one minute ago Use HTML markup and [interpolations](guide/templates/binding#render-dynamic-text-with-text-interpolation). The following code example shows how to use the `plural` clause to express the previous three situations in a `` element. - + Review the following details in the previous code example. @@ -422,14 +419,14 @@ The `gender` property binds the outputs to each of following string values. The `select` clause maps the values to the appropriate translations. The following code example shows `gender` property used with the select clause. - + #### `gender` and `minutes` example Combine different clauses together, such as the `plural` and `select` clauses. The following code example shows nested clauses based on the `gender` and `minutes` examples. - + ## What's next diff --git a/adev-ja/src/content/guide/i18n/translation-files.md b/adev-ja/src/content/guide/i18n/translation-files.md index 6ee0a2559a..11600dde19 100644 --- a/adev-ja/src/content/guide/i18n/translation-files.md +++ b/adev-ja/src/content/guide/i18n/translation-files.md @@ -1,19 +1,19 @@ # Work with translation files -After you prepare a component for translation, use the [`extract-i18n`][CliExtractI18n] [Angular CLI][CliMain] command to extract the marked text in the component into a *source language* file. +After you prepare a component for translation, use the [`extract-i18n`][CliExtractI18n] [Angular CLI][CliMain] command to extract the marked text in the component into a _source language_ file. -The marked text includes text marked with `i18n`, attributes marked with `i18n-`*attribute*, and text tagged with `$localize` as described in [Prepare component for translation][GuideI18nCommonPrepare]. +The marked text includes text marked with `i18n`, attributes marked with `i18n-`_attribute_, and text tagged with `$localize` as described in [Prepare component for translation][GuideI18nCommonPrepare]. Complete the following steps to create and update translation files for your project. 1. [Extract the source language file][GuideI18nCommonTranslationFilesExtractTheSourceLanguageFile]. - 1. Optionally, change the location, format, and name. + 1. Optionally, change the location, format, and name. 1. Copy the source language file to [create a translation file for each language][GuideI18nCommonTranslationFilesCreateATranslationFileForEachLanguage]. 1. [Translate each translation file][GuideI18nCommonTranslationFilesTranslateEachTranslationFile]. 1. Translate plurals and alternate expressions separately. - 1. [Translate plurals][GuideI18nCommonTranslationFilesTranslatePlurals]. - 1. [Translate alternate expressions][GuideI18nCommonTranslationFilesTranslateAlternateExpressions]. - 1. [Translate nested expressions][GuideI18nCommonTranslationFilesTranslateNestedExpressions]. + 1. [Translate plurals][GuideI18nCommonTranslationFilesTranslatePlurals]. + 1. [Translate alternate expressions][GuideI18nCommonTranslationFilesTranslateAlternateExpressions]. + 1. [Translate nested expressions][GuideI18nCommonTranslationFilesTranslateNestedExpressions]. ## Extract the source language file @@ -23,17 +23,17 @@ To extract the source language file, complete the following actions. 1. Change to the root directory of your project. 1. Run the following CLI command. - + The `extract-i18n` command creates a source language file named `messages.xlf` in the root directory of your project. For more information about the XML Localization Interchange File Format \(XLIFF, version 1.2\), see [XLIFF][WikipediaWikiXliff]. Use the following [`extract-i18n`][CliExtractI18n] command options to change the source language file location, format, and file name. -| Command option | Details | -|:--- |:--- | +| Command option | Details | +| :-------------- | :----------------------------------- | | `--format` | Set the format of the output file | -| `--out-file` | Set the name of the output file | +| `--out-file` | Set the name of the output file | | `--output-path` | Set the path of the output directory | ### Change the source language file location @@ -50,8 +50,8 @@ The following example specifies the output path as an option. The `extract-i18n` command creates files in the following translation formats. -| Translation format | Details | File extension | -|:--- |:--- |:--- | +| Translation format | Details | File extension | +| :----------------- | :--------------------------------------------------------------------------------------------------------------- | :---------------- | | ARB | [Application Resource Bundle][GithubGoogleAppResourceBundleWikiApplicationresourcebundlespecification] | `.arb` | | JSON | [JavaScript Object Notation][JsonMain] | `.json` | | XLIFF 1.2 | [XML Localization Interchange File Format, version 1.2][OasisOpenDocsXliffXliffCoreXliffCoreHtml] | `.xlf` | @@ -83,25 +83,25 @@ The following example demonstrates naming the output file. To create a translation file for a locale or language, complete the following actions. 1. [Extract the source language file][GuideI18nCommonTranslationFilesExtractTheSourceLanguageFile]. -1. Make a copy of the source language file to create a *translation* file for each language. -1. Rename the *translation* file to add the locale. +1. Make a copy of the source language file to create a _translation_ file for each language. +1. Rename the _translation_ file to add the locale. - + - messages.xlf --> messages.{locale}.xlf + messages.xlf --> messages.{locale}.xlf - + 1. Create a new directory at your project root named `locale`. - + - src/locale + src/locale - + -1. Move the *translation* file to the new directory. -1. Send the *translation* file to your translator. +1. Move the _translation_ file to the new directory. +1. Send the _translation_ file to your translator. 1. Repeat the above steps for each language you want to add to your application. ### `extract-i18n` example for French @@ -120,32 +120,32 @@ Unless you are fluent in the language and have the time to edit translations, yo 1. Send each translation file to a translator. 1. The translator uses an XLIFF file editor to complete the following actions. - 1. Create the translation. - 1. Edit the translation. + 1. Create the translation. + 1. Edit the translation. ### Translation process example for French -To demonstrate the process, review the `messages.fr.xlf` file in the [Example Angular Internationalization application][GuideI18nExample]. The [Example Angular Internationalization application][GuideI18nExample] includes a French translation for you to edit without a special XLIFF editor or knowledge of French. +To demonstrate the process, review the `messages.fr.xlf` file in the [Example Angular Internationalization application][GuideI18nExample]. The [Example Angular Internationalization application][GuideI18nExample] includes a French translation for you to edit without a special XLIFF editor or knowledge of French. The following actions describe the translation process for French. 1. Open `messages.fr.xlf` and find the first `` element. - This is a *translation unit*, also known as a *text node*, that represents the translation of the `

    ` greeting tag that was previously marked with the `i18n` attribute. + This is a _translation unit_, also known as a _text node_, that represents the translation of the `

    ` greeting tag that was previously marked with the `i18n` attribute. - + - The `id="introductionHeader"` is a [custom ID][GuideI18nOptionalManageMarkedText], but without the `@@` prefix required in the source HTML. + The `id="introductionHeader"` is a [custom ID][GuideI18nOptionalManageMarkedText], but without the `@@` prefix required in the source HTML. 1. Duplicate the `... ` element in the text node, rename it to `target`, and then replace the content with the French text. - + - In a more complex translation, the information and context in the [description and meaning elements][GuideI18nCommonPrepareAddHelpfulDescriptionsAndMeanings] help you choose the right words for translation. + In a more complex translation, the information and context in the [description and meaning elements][GuideI18nCommonPrepareAddHelpfulDescriptionsAndMeanings] help you choose the right words for translation. 1. Translate the other text nodes. - The following example displays the way to translate. + The following example displays the way to translate. - + IMPORTANT: Don't change the IDs for translation units. Each `id` attribute is generated by Angular and depends on the content of the component text and the assigned meaning. @@ -163,9 +163,9 @@ HELPFUL: For language plural rules, see [CLDR plural rules][GithubUnicodeOrgCldr To translate a `plural`, translate the ICU format match values. -* `just now` -* `one minute ago` -* ` minutes ago` +- `just now` +- `one minute ago` +- ` minutes ago` The following example displays the way to translate. @@ -179,7 +179,7 @@ Angular also extracts alternate `select` ICU expressions as separate translation The following example displays a `select` ICU expression in the component template. - + In this example, Angular extracts the expression into two translation units. The first contains the text outside of the `select` clause, and uses a placeholder for `select` \(``\): @@ -222,32 +222,22 @@ The following example displays both translation units after translating. -[CliMain]: cli "CLI Overview and Command Reference | Angular" -[CliExtractI18n]: cli/extract-i18n "ng extract-i18n | CLI | Angular" - -[GuideI18nCommonPrepare]: guide/i18n/prepare "Prepare component for translation | Angular" -[GuideI18nCommonPrepareAddHelpfulDescriptionsAndMeanings]: guide/i18n/prepare#add-helpful-descriptions-and-meanings "Add helpful descriptions and meanings - Prepare component for translation | Angular" - -[GuideI18nCommonTranslationFilesCreateATranslationFileForEachLanguage]: guide/i18n/translation-files#create-a-translation-file-for-each-language "Create a translation file for each language - Work with translation files | Angular" -[GuideI18nCommonTranslationFilesExtractTheSourceLanguageFile]: guide/i18n/translation-files#extract-the-source-language-file "Extract the source language file - Work with translation files | Angular" -[GuideI18nCommonTranslationFilesTranslateAlternateExpressions]: guide/i18n/translation-files#translate-alternate-expressions "Translate alternate expressions - Work with translation files | Angular" -[GuideI18nCommonTranslationFilesTranslateEachTranslationFile]: guide/i18n/translation-files#translate-each-translation-file "Translate each translation file - Work with translation files | Angular" -[GuideI18nCommonTranslationFilesTranslateNestedExpressions]: guide/i18n/translation-files#translate-nested-expressions "Translate nested expressions - Work with translation files | Angular" -[GuideI18nCommonTranslationFilesTranslatePlurals]: guide/i18n/translation-files#translate-plurals "Translate plurals - Work with translation files | Angular" - -[GuideI18nExample]: guide/i18n/example "Example Angular Internationalization application | Angular" - -[GuideI18nOptionalManageMarkedText]: guide/i18n/manage-marked-text "Manage marked text with custom IDs | Angular" - -[GithubGoogleAppResourceBundleWikiApplicationresourcebundlespecification]: https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification "ApplicationResourceBundleSpecification | google/app-resource-bundle | GitHub" - -[GithubUnicodeOrgCldrStagingChartsLatestSupplementalLanguagePluralRulesHtml]: https://cldr.unicode.org/index/cldr-spec/plural-rules "Language Plural Rules - CLDR Charts | Unicode | GitHub" - -[JsonMain]: https://www.json.org "Introducing JSON | JSON" - -[OasisOpenDocsXliffXliffCoreXliffCoreHtml]: http://docs.oasis-open.org/xliff/xliff-core/xliff-core.html "XLIFF Version 1.2 Specification | Oasis Open Docs" -[OasisOpenDocsXliffXliffCoreV20Cos01XliffCoreV20Cose01Html]: http://docs.oasis-open.org/xliff/xliff-core/v2.0/cos01/xliff-core-v2.0-cos01.html "XLIFF Version 2.0 | Oasis Open Docs" - -[UnicodeCldrDevelopmentDevelopmentProcessDesignProposalsXmb]: http://cldr.unicode.org/development/development-process/design-proposals/xmb "XMB | CLDR - Unicode Common Locale Data Repository | Unicode" - -[WikipediaWikiXliff]: https://en.wikipedia.org/wiki/XLIFF "XLIFF | Wikipedia" +[CliMain]: cli 'CLI Overview and Command Reference | Angular' +[CliExtractI18n]: cli/extract-i18n 'ng extract-i18n | CLI | Angular' +[GuideI18nCommonPrepare]: guide/i18n/prepare 'Prepare component for translation | Angular' +[GuideI18nCommonPrepareAddHelpfulDescriptionsAndMeanings]: guide/i18n/prepare#add-helpful-descriptions-and-meanings 'Add helpful descriptions and meanings - Prepare component for translation | Angular' +[GuideI18nCommonTranslationFilesCreateATranslationFileForEachLanguage]: guide/i18n/translation-files#create-a-translation-file-for-each-language 'Create a translation file for each language - Work with translation files | Angular' +[GuideI18nCommonTranslationFilesExtractTheSourceLanguageFile]: guide/i18n/translation-files#extract-the-source-language-file 'Extract the source language file - Work with translation files | Angular' +[GuideI18nCommonTranslationFilesTranslateAlternateExpressions]: guide/i18n/translation-files#translate-alternate-expressions 'Translate alternate expressions - Work with translation files | Angular' +[GuideI18nCommonTranslationFilesTranslateEachTranslationFile]: guide/i18n/translation-files#translate-each-translation-file 'Translate each translation file - Work with translation files | Angular' +[GuideI18nCommonTranslationFilesTranslateNestedExpressions]: guide/i18n/translation-files#translate-nested-expressions 'Translate nested expressions - Work with translation files | Angular' +[GuideI18nCommonTranslationFilesTranslatePlurals]: guide/i18n/translation-files#translate-plurals 'Translate plurals - Work with translation files | Angular' +[GuideI18nExample]: guide/i18n/example 'Example Angular Internationalization application | Angular' +[GuideI18nOptionalManageMarkedText]: guide/i18n/manage-marked-text 'Manage marked text with custom IDs | Angular' +[GithubGoogleAppResourceBundleWikiApplicationresourcebundlespecification]: https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification 'ApplicationResourceBundleSpecification | google/app-resource-bundle | GitHub' +[GithubUnicodeOrgCldrStagingChartsLatestSupplementalLanguagePluralRulesHtml]: https://cldr.unicode.org/index/cldr-spec/plural-rules 'Language Plural Rules - CLDR Charts | Unicode | GitHub' +[JsonMain]: https://www.json.org 'Introducing JSON | JSON' +[OasisOpenDocsXliffXliffCoreXliffCoreHtml]: https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html 'XLIFF Version 1.2 Specification | Oasis Open Docs' +[OasisOpenDocsXliffXliffCoreV20Cos01XliffCoreV20Cose01Html]: http://docs.oasis-open.org/xliff/xliff-core/v2.0/cos01/xliff-core-v2.0-cos01.html 'XLIFF Version 2.0 | Oasis Open Docs' +[UnicodeCldrDevelopmentDevelopmentProcessDesignProposalsXmb]: http://cldr.unicode.org/development/development-process/design-proposals/xmb 'XMB | CLDR - Unicode Common Locale Data Repository | Unicode' +[WikipediaWikiXliff]: https://en.wikipedia.org/wiki/XLIFF 'XLIFF | Wikipedia' diff --git a/adev-ja/src/content/guide/ngmodules/overview.md b/adev-ja/src/content/guide/ngmodules/overview.md index 778e1b3279..c0b4bbdfd7 100644 --- a/adev-ja/src/content/guide/ngmodules/overview.md +++ b/adev-ja/src/content/guide/ngmodules/overview.md @@ -2,7 +2,7 @@ IMPORTANT: The Angular team recommends using [standalone components](guide/components/anatomy-of-components#-imports-in-the-component-decorator) instead of `NgModule` for all new code. Use this guide to understand existing code built with `@NgModule`. -An NgModule is a class marked by the `@NgModule` decorator. This decorator accepts *metadata* that tells Angular how to compile component templates and configure dependency injection. +An NgModule is a class marked by the `@NgModule` decorator. This decorator accepts _metadata_ that tells Angular how to compile component templates and configure dependency injection. ```typescript import {NgModule} from '@angular/core'; @@ -14,8 +14,9 @@ export class CustomMenuModule { } ``` An NgModule has two main responsibilities: -* Declaring components, directives, and pipes that belong to the NgModule -* Add providers to the injector for components, directives, and pipes that import the NgModule + +- Declaring components, directives, and pipes that belong to the NgModule +- Add providers to the injector for components, directives, and pipes that import the NgModule ## Declarations @@ -80,27 +81,27 @@ The `imports` array accepts other NgModules, as well as standalone components, d An NgModule can _export_ its declared components, directives, and pipes such that they're available to other components and NgModules. - ```typescript +```typescript @NgModule({ - imports: [PopupTrigger, SelectionIndicator], - declarations: [CustomMenu, CustomMenuItem], + imports: [PopupTrigger, SelectionIndicator], + declarations: [CustomMenu, CustomMenuItem], - // Make CustomMenu and CustomMenuItem available to - // components and NgModules that import CustomMenuModule. - exports: [CustomMenu, CustomMenuItem], + // Make CustomMenu and CustomMenuItem available to + // components and NgModules that import CustomMenuModule. + exports: [CustomMenu, CustomMenuItem], }) export class CustomMenuModule { } ``` The `exports` property is not limited to declarations, however. An NgModule can also export any other components, directives, pipes, and NgModules that it imports. - ```typescript +```typescript @NgModule({ - imports: [PopupTrigger, SelectionIndicator], - declarations: [CustomMenu, CustomMenuItem], + imports: [PopupTrigger, SelectionIndicator], + declarations: [CustomMenu, CustomMenuItem], - // Also make PopupTrigger available to any component or NgModule that imports CustomMenuModule. - exports: [CustomMenu, CustomMenuItem, PopupTrigger], + // Also make PopupTrigger available to any component or NgModule that imports CustomMenuModule. + exports: [CustomMenu, CustomMenuItem, PopupTrigger], }) export class CustomMenuModule { } ``` @@ -110,8 +111,9 @@ export class CustomMenuModule { } TIP: See the [Dependency Injection guide](guide/di) for information on dependency injection and providers. An `NgModule` can specify `providers` for injected dependencies. These providers are available to: -* Any standalone component, directive, or pipe that imports the NgModule, and -* The `declarations` and `providers` of any _other_ NgModule that imports the NgModule. + +- Any standalone component, directive, or pipe that imports the NgModule, and +- The `declarations` and `providers` of any _other_ NgModule that imports the NgModule. ```typescript @NgModule({ @@ -133,10 +135,11 @@ export class UserProfileModule { } ``` In the example above: -* The `CustomMenuModule` provides `OverlayManager`. -* The `CustomMenu` and `CustomMenuItem` components can inject `OverlayManager` because they're declared in `CustomMenuModule`. -* `UserProfile` can inject `OverlayManager` because its NgModule imports `CustomMenuModule`. -* `UserDataClient` can inject `OverlayManager` because its NgModule imports `CustomMenuModule`. + +- The `CustomMenuModule` provides `OverlayManager`. +- The `CustomMenu` and `CustomMenuItem` components can inject `OverlayManager` because they're declared in `CustomMenuModule`. +- `UserProfile` can inject `OverlayManager` because its NgModule imports `CustomMenuModule`. +- `UserDataClient` can inject `OverlayManager` because its NgModule imports `CustomMenuModule`. ### The `forRoot` and `forChild` pattern diff --git a/adev-ja/src/content/guide/routing/customizing-route-behavior.md b/adev-ja/src/content/guide/routing/customizing-route-behavior.md index 6ae475fc59..a489a8e15d 100644 --- a/adev-ja/src/content/guide/routing/customizing-route-behavior.md +++ b/adev-ja/src/content/guide/routing/customizing-route-behavior.md @@ -12,6 +12,113 @@ Route customization can become valuable when your application needs: NOTE: Before implementing custom strategies, ensure the default router behavior doesn't meet your needs. Angular's default routing is optimized for common use cases and provides the best balance of performance and simplicity. Customizing route strategies can create additional code complexity and have performance implications on memory usage if not carefully managed. +## Router configuration options + +The `withRouterConfig` or `RouterModule.forRoot` allows providing additional `RouterConfigOptions` to adjust the Router’s behavior. + +### Handle canceled navigations + +`canceledNavigationResolution` controls how the Router restores browser history when a navigation is canceled. The default value is `'replace'`, which reverts to the pre-navigation URL with `location.replaceState`. In practice, this means that any time the address bar has already been updated for the navigation, such as with the browser back or forward buttons, the history entry is overwritten with the "rollback" if the navigation fails or is rejected by a guard. +Switching to `'computed'` keeps the in-flight history index in sync with the Angular navigation, so canceling a back button navigation triggers a forward navigation (and vice versa) to return to the original page. + +This setting is most helpful when your app uses `urlUpdateStrategy: 'eager'` or when guards frequently cancel popstate navigations initiated by the browser. + +```ts +provideRouter(routes, withRouterConfig({ canceledNavigationResolution: 'computed' })); +``` + +### React to same-URL navigations + +`onSameUrlNavigation` configures what should happen when the user asks to navigate to the current URL. The default `'ignore'` skips work, while `'reload'` re-runs guards and resolvers and refreshes component instances. + +This is useful when you want repeated clicks on a list filter, left-nav item, or refresh button to trigger new data retrieval even though the URL does not change. + +```ts +provideRouter(routes, withRouterConfig({ onSameUrlNavigation: 'reload' })); +``` + +You can also control this behavior on individual navigations rather than globally. This allows you to keep the keep the default of `'ignore'` while selectively enabling reload behavior for specific use cases: + +```ts +router.navigate(['/some-path'], { onSameUrlNavigation: 'reload' }); +``` + +### Control parameter inheritance + +`paramsInheritanceStrategy` defines how route parameters and data flow from parent routes. + +With the default `'emptyOnly'`, child routes inherit params only when their path is empty or the parent does not declare a component. + +```ts +provideRouter(routes, withRouterConfig({ paramsInheritanceStrategy: 'always' })); +``` + +```ts +export const routes: Routes = [ + { + path: 'org/:orgId', + component: Organization, + children: [ + { + path: 'projects/:projectId', + component: Project, + children: [ + { + path: 'customers/:customerId', + component: Customer + } + ] + } + ] + } +]; +``` + +```ts +@Component({ /* ... */}) +export class CustomerComponent { + private route = inject(ActivatedRoute); + + orgId = this.route.parent?.parent?.snapshot.params['orgId']; + projectId = this.route.parent?.snapshot.params['projectId']; + customerId = this.route.snapshot.params['customerId']; +} +``` + +Using `'always'` ensures matrix parameters, route data, and resolved values are available further down the route tree—handy when you share contextual identifiers across feature areas such as `/org/:orgId/projects/:projectId/customers/:customerId`. + +```ts +@Component({ /* ... */}) +export class CustomerComponent { + private route = inject(ActivatedRoute); + + // All parent parameters are available directly + orgId = this.route.snapshot.params['orgId']; + projectId = this.route.snapshot.params['projectId']; + customerId = this.route.snapshot.params['customerId']; +} +``` + +### Decide when the URL updates + +`urlUpdateStrategy` determines when Angular writes to the browser address bar. The default `'deferred'` waits for a successful navigation before changing the URL. Use `'eager'` to update immediately when navigation starts. Eager updates make it easier to surface the attempted URL if navigation fails due to guards or errors, but can briefly show an in-progress URL if you have long-running guards. + +Consider this when your analytics pipeline needs to see the attempted route even if guards block it. + +```ts +provideRouter(routes, withRouterConfig({ urlUpdateStrategy: 'eager' })); +``` + +### Choose default query parameter handling + +`defaultQueryParamsHandling` sets the fallback behavior for `Router.createUrlTree` when the call does not specify `queryParamsHandling`. `'replace'` is the default and swaps out the existing query string. `'merge'` combines the provided values with the current ones, and `'preserve'` keeps the existing query parameters unless you explicitly supply new ones. + +```ts +provideRouter(routes, withRouterConfig({ defaultQueryParamsHandling: 'merge' })); +``` + +This is especially helpful for search and filter pages to automatically retain existing filters when additional parameters are provided. + Angular Router exposes four main areas for customization: @@ -53,12 +160,12 @@ The `RouteReuseStrategy` class provides five methods that control the lifecycle The following example demonstrates a custom route reuse strategy that selectively preserves component state based on route metadata: ```ts -import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router'; +import { RouteReuseStrategy, Route, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router'; import { Injectable } from '@angular/core'; @Injectable() export class CustomRouteReuseStrategy implements RouteReuseStrategy { - private handlers = new Map(); + private handlers = new Map(); shouldDetach(route: ActivatedRouteSnapshot): boolean { // Determines if a route should be stored for later reuse @@ -90,12 +197,14 @@ export class CustomRouteReuseStrategy implements RouteReuseStrategy { return future.routeConfig === curr.routeConfig; } - private getRouteKey(route: ActivatedRouteSnapshot): string { - return route.routeConfig ?? ''; + private getRouteKey(route: ActivatedRouteSnapshot): Route | null { + return route.routeConfig; } } ``` +NOTE: Avoid using the route path as the key when `canMatch` guards are involved, as it may lead to duplicate entries. + ### Configuring a route to use a custom route reuse strategy Routes can opt into reuse behavior through route configuration metadata. This approach keeps the reuse logic separate from component code, making it easy to adjust behavior without modifying components: @@ -339,7 +448,7 @@ export const routes: Routes = [ The component receives the extracted parameters through route inputs: -```ts +```angular-ts import { Component, input, inject } from '@angular/core'; import { resource } from '@angular/core'; diff --git a/adev-ja/src/content/guide/tailwind.md b/adev-ja/src/content/guide/tailwind.md index b5b8094f79..c7b9d078e6 100644 --- a/adev-ja/src/content/guide/tailwind.md +++ b/adev-ja/src/content/guide/tailwind.md @@ -8,18 +8,29 @@ First, create a new Angular project if you don't have one set up already. - +```shell ng new my-project cd my-project - +``` ### 2. Install Tailwind CSS Next, open a terminal in your Angular project's root directory and run the following command to install Tailwind CSS and its peer dependencies: - -npm install tailwindcss @tailwindcss/postcss postcss - + + + npm install tailwindcss @tailwindcss/postcss postcss + + + yarn add tailwindcss @tailwindcss/postcss postcss + + + pnpm add tailwindcss @tailwindcss/postcss postcss + + + bun add tailwindcss @tailwindcss/postcss postcss + + ### 3. Configure PostCSS Plugins @@ -66,4 +77,4 @@ Run your build process with `ng serve` and you should see the styled heading. ## Additional Resources -- [Tailwind CSS Documentation](https://tailwindcss.com/docs) \ No newline at end of file +- [Tailwind CSS Documentation](https://tailwindcss.com/docs) diff --git a/adev-ja/src/content/kitchen-sink.md b/adev-ja/src/content/kitchen-sink.md index fb2f194eb9..8d07f9ae77 100644 --- a/adev-ja/src/content/kitchen-sink.md +++ b/adev-ja/src/content/kitchen-sink.md @@ -4,11 +4,11 @@ This is a visual list of all custom components and styles for Angular.dev. As a design system, this page contains visual and Markdown authoring guidance for: -* Custom Angular docs elements: [`docs-card`](#cards), [`docs-callout`](#callouts), [`docs-pill`](#pills), and [`docs-steps`](#workflow) -* Custom text elements: [alerts](#alerts) -* Code examples: [`docs-code`](#code) -* Built-in Markdown styled elements: links, lists, [headers](#headers), [horizontal lines](#horizontal-line-divider), [tables](#tables) -* and more! +- Custom Angular docs elements: [`docs-card`](#cards), [`docs-callout`](#callouts), [`docs-pill`](#pills), and [`docs-steps`](#workflow) +- Custom text elements: [alerts](#alerts) +- Code examples: [`docs-code`](#code) +- Built-in Markdown styled elements: links, lists, [headers](#headers-h2), [horizontal lines](#horizontal-line-divider) +- and more! Get ready to: @@ -42,13 +42,13 @@ Get ready to: ### `` Attributes -| Attributes | Details | -|:--- |:--- | -| `` | All cards must be nested inside a container | -| `title` | Card title | -| card body contents | Anything between `` and `` | -| `link` | (Optional) Call to Action link text | -| `href` | (Optional) Call to Action link href | +| Attributes | Details | +| :---------------------- | :------------------------------------------------ | +| `` | All cards must be nested inside a container | +| `title` | Card title | +| card body contents | Anything between `` and `` | +| `link` | (Optional) Call to Action link text | +| `href` | (Optional) Call to Action link href | ## Callouts @@ -67,7 +67,7 @@ Get ready to: ### `` Attributes | Attributes | Details | -|:--- |:--- | +| :----------------------------------------------- | :-------------------------------------------------------- | | `title` | Callout title | | card body contents | Anything between `` and `` | | `helpful` (default) \| `critical` \| `important` | (Optional) Adds styling and icons based on severity level | @@ -76,7 +76,7 @@ Get ready to: Pill rows are helpful as a sort of navigation with links to helpful resources. - + @@ -87,11 +87,11 @@ Pill rows are helpful as a sort of navigation with links to helpful resources. ### `` Attributes -| Attributes | Details | -|:--- |:--- | -| `` element. import { Component } from '@angular/core'; @Component({ - selector: 'example-code', - template: '

    Hello World!

    ', +selector: 'example-code', +template: '

    Hello World!

    ', }) export class ComponentOverviewComponent {}
    @@ -157,25 +157,25 @@ Here's a code example fully styled: We also have styling for the terminal, just set the language as `shell`: - - npm install @angular/material --save - +```shell +npm install @angular/material --save +``` #### `` Attributes -| Attributes | Type | Details | -|:--- |:--- |:--- | -| code | `string` | Anything between tags is treated as code | -| `path` | `string` | Path to code example (root: `content/examples/`) | -| `header` | `string` | Title of the example (default: `file-name`) | -| `language` | `string` | code language | -| `linenums` | `boolean` | (False) displays line numbers | -| `highlight` | `string of number[]` | lines highlighted | -| `diff` | `string` | path to changed code | -| `visibleLines` | `string of number[]` | range of lines for collapse mode | -| `visibleRegion` | `string` | **DEPRECATED** FOR `visibleLines` | -| `preview` | `boolean` | (False) display preview | -| `hideCode` | `boolean` | (False) Whether to collapse code example by default. | +| Attributes | Type | Details | +| :-------------- | :------------------- | :--------------------------------------------------- | +| code | `string` | Anything between tags is treated as code | +| `path` | `string` | Path to code example (root: `content/examples/`) | +| `header` | `string` | Title of the example (default: `file-name`) | +| `language` | `string` | code language | +| `linenums` | `boolean` | (False) displays line numbers | +| `highlight` | `string of number[]` | lines highlighted | +| `diff` | `string` | path to changed code | +| `visibleLines` | `string of number[]` | range of lines for collapse mode | +| `visibleRegion` | `string` | **DEPRECATED** FOR `visibleLines` | +| `preview` | `boolean` | (False) display preview | +| `hideCode` | `boolean` | (False) Whether to collapse code example by default. | ### Multifile examples @@ -184,27 +184,27 @@ You can create multifile examples by wrapping the examples inside a ` - - - #### `` Attributes -| Attributes | Type | Details | -|:--- |:--- |:--- | -| body contents | `string` | nested tabs of `docs-code` examples | -| `path` | `string` | Path to code example for preview and external link | -| `preview` | `boolean` | (False) display preview | -| `hideCode` | `boolean` | (False) Whether to collapse code example by default. | +| Attributes | Type | Details | +| :------------ | :-------- | :--------------------------------------------------- | +| body contents | `string` | nested tabs of `docs-code` examples | +| `path` | `string` | Path to code example for preview and external link | +| `preview` | `boolean` | (False) display preview | +| `hideCode` | `boolean` | (False) Whether to collapse code example by default. | ### Adding `preview` to your code example @@ -212,17 +212,45 @@ Adding the `preview` flag builds a running example of the code below the code sn NOTE: `preview` only works with standalone. +### Styling example previews with Tailwind CSS + +Tailwind utility classes can be used within code examples. + + + + + + +## Tabs + + + + + + + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus metus blandit semper faucibus. Sed blandit diam quis tellus maximus, ac scelerisque ex egestas. Ut euismod lobortis mauris pretium iaculis. Quisque ullamcorper, elit ut lacinia blandit, magna sem finibus urna, vel suscipit tortor dolor id risus. + + + ## Workflow Style numbered steps using ``. Numbering is created using CSS (handy!). ### `` and `` Attributes -| Attributes | Details | -|:--- |:--- | -| `` | All steps must be nested inside a workflow | -| `title` | Step title | -| step body contents | Anything between `` and `` | +| Attributes | Details | +| :----------------- | :------------------------------------------------ | +| `` | All steps must be nested inside a workflow | +| `title` | Step title | +| step body contents | Anything between `` and `` | Steps must start on a new line, and can contain `docs-code`s and other nested elements and styles. @@ -231,44 +259,47 @@ Steps must start on a new line, and can contain `docs-code`s and other nested el You use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. - To install the Angular CLI, open a terminal window and run the following command: +To install the Angular CLI, open a terminal window and run the following command: + +```shell +npm install -g @angular/cli +``` - - npm install -g @angular/cli - You develop apps in the context of an Angular workspace. - To create a new workspace and initial starter app: +To create a new workspace and initial starter app: + +- Run the CLI command `ng new` and provide the name `my-app`, as shown here: -* Run the CLI command `ng new` and provide the name `my-app`, as shown here: - - ng new my-app - + ```shell + ng new my-app + ``` -* The ng new command prompts you for information about features to include in the initial app. Accept the defaults by pressing the Enter or Return key. +- The ng new command prompts you for information about features to include in the initial app. Accept the defaults by pressing the Enter or Return key. The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a few minutes. The CLI creates a new workspace and a simple Welcome app, ready to run. - + The Angular CLI includes a server, for you to build and serve your app locally. - 1. Navigate to the workspace folder, such as `my-app`. - 2. Run the following command: - - cd my-app - ng serve --open - +1. Navigate to the workspace folder, such as `my-app`. +2. Run the following command: + + ```shell + cd my-app + ng serve --open + ``` - The `ng serve` command launches the server, watches your files, and rebuilds the app as you make changes to those files. +The `ng serve` command launches the server, watches your files, and rebuilds the app as you make changes to those files. - The `--open` (or just `-o`) option automatically opens your browser to . - If your installation and setup was successful, you should see a page similar to the following. +The `--open` (or just `-o`) option automatically opens your browser to . +If your installation and setup was successful, you should see a page similar to the following. @@ -288,7 +319,7 @@ Steps must start on a new line, and can contain `docs-code`s and other nested el You can add images using the semantic Markdown image: -![Rhubarb the cat](assets/images/kitchen-sink/rhubarb.jpg "Optional title") +![Rhubarb the cat](assets/images/kitchen-sink/rhubarb.jpg 'Optional title') ### Add `#small` and `#medium` to change the image size @@ -328,7 +359,7 @@ Write diagrams and charts using [Mermaid](http://mermaid.js.org/) by setting the ## Horizontal Line Divider -This can be used to separate page sections, like we're about to do below. These styles will be added by default, nothing custom needed. +This can be used to separate page sections, like we're about to do below. These styles will be added by default, nothing custom needed.
    diff --git a/adev-ja/src/content/reference/cli.md b/adev-ja/src/content/reference/cli.md index 59fcc1a3cf..16b419bb17 100644 --- a/adev-ja/src/content/reference/cli.md +++ b/adev-ja/src/content/reference/cli.md @@ -1,21 +1,21 @@ # CLI Reference -| Command | Alias | Description | -|:--- |:--- |:--- | -| [`add`](cli/add) | | Adds support for an external library to your project. | -| [`analytics`](cli/analytics) | | Configures the gathering of Angular CLI usage metrics. | -| [`build`](cli/build) | `b` | Compiles an Angular application or library into an output directory named dist/ at the given output path. | -| [`cache`](cli/cache) | | Configure persistent disk cache and retrieve cache statistics. | -| [`completion`](cli/completion) | | Set up Angular CLI autocompletion for your terminal. | -| [`config`](cli/config) | | Retrieves or sets Angular configuration values in the angular.json file for the workspace. | -| [`deploy`](cli/deploy) | | Invokes the deploy builder for a specified project or for the default project in the workspace. | -| [`e2e`](cli/e2e) | `e` | Builds and serves an Angular application, then runs end-to-end tests. | -| [`extract-i18n`](cli/extract-i18n)| | Extracts i18n messages from source code. | -| [`generate`](cli/generate) | `g` | Generates and/or modifies files based on a schematic. | -| [`lint`](cli/lint) | | Runs linting tools on Angular application code in a given project folder. | -| [`new`](cli/new) | `n` | Creates a new Angular workspace. | -| [`run`](cli/run) | | Runs an Architect target with an optional custom builder configuration defined in your project. | -| [`serve`](cli/serve) | `s`, `dev` | Builds and serves your application, rebuilding on file changes. | -| [`test`](cli/test) | `t` | Runs unit tests in a project. | -| [`update`](cli/update) | | Updates your workspace and its dependencies. See https://angular.dev/update-guide/. | -| [`version`](cli/version) | `v` | Outputs Angular CLI version. | +| Command | Alias | Description | +| :--------------------------------- | :--------- | :-------------------------------------------------------------------------------------------------------- | +| [`add`](cli/add) | | Adds support for an external library to your project. | +| [`analytics`](cli/analytics) | | Configures the gathering of Angular CLI usage metrics. | +| [`build`](cli/build) | `b` | Compiles an Angular application or library into an output directory named dist/ at the given output path. | +| [`cache`](cli/cache) | | Configure persistent disk cache and retrieve cache statistics. | +| [`completion`](cli/completion) | | Set up Angular CLI autocompletion for your terminal. | +| [`config`](cli/config) | | Retrieves or sets Angular configuration values in the angular.json file for the workspace. | +| [`deploy`](cli/deploy) | | Invokes the deploy builder for a specified project or for the default project in the workspace. | +| [`e2e`](cli/e2e) | `e` | Builds and serves an Angular application, then runs end-to-end tests. | +| [`extract-i18n`](cli/extract-i18n) | | Extracts i18n messages from source code. | +| [`generate`](cli/generate) | `g` | Generates and/or modifies files based on a schematic. | +| [`lint`](cli/lint) | | Runs linting tools on Angular application code in a given project folder. | +| [`new`](cli/new) | `n` | Creates a new Angular workspace. | +| [`run`](cli/run) | | Runs an Architect target with an optional custom builder configuration defined in your project. | +| [`serve`](cli/serve) | `s`, `dev` | Builds and serves your application, rebuilding on file changes. | +| [`test`](cli/test) | `t` | Runs unit tests in a project. | +| [`update`](cli/update) | | Updates your workspace and its dependencies. See https://angular.dev/update-guide/. | +| [`version`](cli/version) | `v` | Outputs Angular CLI version. | diff --git a/adev-ja/src/content/reference/configs/angular-compiler-options.md b/adev-ja/src/content/reference/configs/angular-compiler-options.md index 09731158a0..d036086242 100644 --- a/adev-ja/src/content/reference/configs/angular-compiler-options.md +++ b/adev-ja/src/content/reference/configs/angular-compiler-options.md @@ -30,12 +30,12 @@ Modifies how Angular-specific annotations are emitted to improve tree-shaking. Non-Angular annotations are not affected. One of `static fields` or `decorators`. The default value is `static fields`. -* By default, the compiler replaces decorators with a static field in the class, which allows advanced tree-shakers like [Closure compiler](https://github.com/google/closure-compiler) to remove unused classes -* The `decorators` value leaves the decorators in place, which makes compilation faster. - TypeScript emits calls to the `__decorate` helper. - Use `--emitDecoratorMetadata` for runtime reflection. +- By default, the compiler replaces decorators with a static field in the class, which allows advanced tree-shakers like [Closure compiler](https://github.com/google/closure-compiler) to remove unused classes +- The `decorators` value leaves the decorators in place, which makes compilation faster. + TypeScript emits calls to the `__decorate` helper. + Use `--emitDecoratorMetadata` for runtime reflection. - HELPFUL: That the resulting code cannot tree-shake properly. + HELPFUL: That the resulting code cannot tree-shake properly. ### `annotateForClosureCompiler` @@ -51,8 +51,8 @@ Default is `false`. Specifies the compilation mode to use. The following modes are available: -| Modes | Details | -|:--- |:--- | +| Modes | Details | +| :---------- | :-------------------------------------------------------------------------------------------------- | | `'full'` | Generates fully AOT-compiled code according to the version of Angular that is currently being used. | | `'partial'` | Generates code in a stable, but intermediate form suitable for a published library. | @@ -231,4 +231,4 @@ The `ngc` command is a wrapper around TypeScript's `tsc` compiler command. The A Besides the configuration file, you can also use [`tsc` command line options](https://www.typescriptlang.org/docs/handbook/compiler-options.html) to configure `ngc`. -[GuideI18nCommonPrepareMarkTextInComponentTemplate]: guide/i18n/prepare#mark-text-in-component-template "Mark text in component template - Prepare component for translation | Angular" +[GuideI18nCommonPrepareMarkTextInComponentTemplate]: guide/i18n/prepare#mark-text-in-component-template 'Mark text in component template - Prepare component for translation | Angular' diff --git a/adev-ja/src/content/reference/configs/npm-packages.md b/adev-ja/src/content/reference/configs/npm-packages.md index 8e40d95186..a6abb9f014 100644 --- a/adev-ja/src/content/reference/configs/npm-packages.md +++ b/adev-ja/src/content/reference/configs/npm-packages.md @@ -1,11 +1,11 @@ # Workspace npm dependencies -The Angular Framework, Angular CLI, and components used by Angular applications are packaged as [npm packages](https://docs.npmjs.com/getting-started/what-is-npm "What is npm?") and distributed using the [npm registry](https://docs.npmjs.com). +The Angular Framework, Angular CLI, and components used by Angular applications are packaged as [npm packages](https://docs.npmjs.com/getting-started/what-is-npm 'What is npm?') and distributed using the [npm registry](https://docs.npmjs.com). You can download and install these npm packages by using the [npm CLI client](https://docs.npmjs.com/cli/install). By default, Angular CLI uses the npm client. -HELPFUL: See [Local Environment Setup](tools/cli/setup-local "Setting up for Local Development") for information about the required versions and installation of `Node.js` and `npm`. +HELPFUL: See [Local Environment Setup](tools/cli/setup-local 'Setting up for Local Development') for information about the required versions and installation of `Node.js` and `npm`. If you already have projects running on your machine that use other versions of Node.js and npm, consider using [nvm](https://github.com/creationix/nvm) to manage the multiple versions of Node.js and npm. @@ -17,7 +17,7 @@ The CLI command `ng new` creates a `package.json` file when it creates the new w This `package.json` is used by all projects in the workspace, including the initial application project that is created by the CLI when it creates the workspace. Libraries created with `ng generate library` will include their own `package.json` file. -Initially, this `package.json` includes *a starter set of packages*, some of which are required by Angular and others that support common application scenarios. +Initially, this `package.json` includes _a starter set of packages_, some of which are required by Angular and others that support common application scenarios. You add packages to `package.json` as your application evolves. ## Default Dependencies @@ -25,19 +25,19 @@ You add packages to `package.json` as your application evolves. The following Angular packages are included as dependencies in the default `package.json` file for a new Angular workspace. For a complete list of Angular packages, see the [API reference](api). -| Package name | Details | -|:--- |:--- | -| [`@angular/animations`](api#animations) | Angular's legacy animations library makes it easy to define and apply animation effects such as page and list transitions. For more information, see the [Legacy Animations guide](guide/legacy-animations). | -| [`@angular/common`](api#common) | The commonly-needed services, pipes, and directives provided by the Angular team. | -| `@angular/compiler` | Angular's template compiler. It understands Angular templates and can convert them to code that makes the application run. | -| `@angular/compiler-cli` | Angular's compiler which is invoked by the Angular CLI's `ng build` and `ng serve` commands. It processes Angular templates with `@angular/compiler` inside a standard TypeScript compilation. | -| [`@angular/core`](api#core) | Critical runtime parts of the framework that are needed by every application. Includes all metadata decorators such as `@Component`, dependency injection, and component lifecycle hooks. | -| [`@angular/forms`](api#forms) | Support for both [template-driven](guide/forms) and [reactive forms](guide/forms/reactive-forms). See [Introduction to forms](guide/forms). | -| [`@angular/platform-browser`](api#platform-browser) | Everything DOM and browser related, especially the pieces that help render into the DOM. | -| [`@angular/platform-browser-dynamic`](api#platform-browser-dynamic) | Includes [providers](api/core/Provider) and methods to compile and run the application on the client using the [JIT compiler](tools/cli/aot-compiler#choosing-a-compiler). | -| [`@angular/router`](api#router) | The router module navigates among your application pages when the browser URL changes. For more information, see [Routing and Navigation](guide/routing). | -| [`@angular/cli`](https://github.com/angular/angular-cli) | Contains the Angular CLI binary for running `ng` commands. | -| [`@angular-devkit/build-angular`](https://www.npmjs.com/package/@angular-devkit/build-angular) | Contains default CLI builders for bundling, testing, and serving Angular applications and libraries. | -| [`rxjs`](https://www.npmjs.com/package/rxjs) | A library for reactive programming using `Observables`. | -| [`zone.js`](https://github.com/angular/zone.js) | Angular relies on `zone.js`` to run Angular's change detection processes when native JavaScript operations raise events. | -| [`typescript`](https://www.npmjs.com/package/typescript) | The TypeScript compiler, language server, and built-in type definitions. | +| Package name | Details | +| :--------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [`@angular/animations`](api#animations) | Angular's legacy animations library makes it easy to define and apply animation effects such as page and list transitions. For more information, see the [Legacy Animations guide](guide/legacy-animations). | +| [`@angular/common`](api#common) | The commonly-needed services, pipes, and directives provided by the Angular team. | +| `@angular/compiler` | Angular's template compiler. It understands Angular templates and can convert them to code that makes the application run. | +| `@angular/compiler-cli` | Angular's compiler which is invoked by the Angular CLI's `ng build` and `ng serve` commands. It processes Angular templates with `@angular/compiler` inside a standard TypeScript compilation. | +| [`@angular/core`](api#core) | Critical runtime parts of the framework that are needed by every application. Includes all metadata decorators such as `@Component`, dependency injection, and component lifecycle hooks. | +| [`@angular/forms`](api#forms) | Support for both [template-driven](guide/forms) and [reactive forms](guide/forms/reactive-forms). See [Introduction to forms](guide/forms). | +| [`@angular/platform-browser`](api#platform-browser) | Everything DOM and browser related, especially the pieces that help render into the DOM. | +| [`@angular/platform-browser-dynamic`](api#platform-browser-dynamic) | Includes [providers](api/core/Provider) and methods to compile and run the application on the client using the [JIT compiler](tools/cli/aot-compiler#choosing-a-compiler). | +| [`@angular/router`](api#router) | The router module navigates among your application pages when the browser URL changes. For more information, see [Routing and Navigation](guide/routing). | +| [`@angular/cli`](https://github.com/angular/angular-cli) | Contains the Angular CLI binary for running `ng` commands. | +| [`@angular-devkit/build-angular`](https://www.npmjs.com/package/@angular-devkit/build-angular) | Contains default CLI builders for bundling, testing, and serving Angular applications and libraries. | +| [`rxjs`](https://www.npmjs.com/package/rxjs) | A library for reactive programming using `Observables`. | +| [`zone.js`](https://github.com/angular/zone.js) | Angular relies on `zone.js`` to run Angular's change detection processes when native JavaScript operations raise events. | +| [`typescript`](https://www.npmjs.com/package/typescript) | The TypeScript compiler, language server, and built-in type definitions. | diff --git a/adev-ja/src/content/reference/configs/workspace-config.md b/adev-ja/src/content/reference/configs/workspace-config.md index 1dd1eb0fa9..a122c85354 100644 --- a/adev-ja/src/content/reference/configs/workspace-config.md +++ b/adev-ja/src/content/reference/configs/workspace-config.md @@ -12,7 +12,7 @@ You can also override defaults set at the project level using the command line. The following properties, at the top-level of the file, configure the workspace. | Properties | Details | -|:--- |:--- | +| :--------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `version` | The configuration-file version. | | `newProjectRoot` | Path where new projects are created through tools like `ng generate application` or `ng generate library`. Path can be absolute or relative to the workspace directory. Defaults to `projects` | | `cli` | A set of options that customize the [Angular CLI](tools/cli). See [Angular CLI configuration options](#angular-cli-configuration-options) below. | @@ -24,9 +24,11 @@ The initial application that you create with `ng new app-name` is listed under " When you create a library project with `ng generate library`, the library project is also added to the `projects` section. HELPFUL: The `projects` section of the configuration file does not correspond exactly to the workspace file structure. + -* The initial application created by `ng new` is at the top level of the workspace file structure. -* Other applications and libraries are under the `projects` directory by default. + +- The initial application created by `ng new` is at the top level of the workspace file structure. +- Other applications and libraries are under the `projects` directory by default. For more information, see [Workspace and project file structure](reference/configs/file-structure). @@ -34,26 +36,26 @@ For more information, see [Workspace and project file structure](reference/confi The following properties are a set of options that customize the Angular CLI. -| Property | Details | Value type | Default value | -|:--- |:--- |:--- |:--- | -| `analytics` | Share anonymous usage data with the Angular Team. A boolean value indicates whether or not to share data, while a UUID string shares data using a pseudonymous identifier. | `boolean` \| `string` | `false` | -| `cache` | Control [persistent disk cache](cli/cache) used by [Angular CLI Builders](tools/cli/cli-builder). | [Cache options](#cache-options) | `{}` | -| `schematicCollections`| List schematics collections to use in `ng generate`. | `string[]` | `[]` | -| `packageManager` | The preferred package manager tool to use. | `npm` \| `cnpm` \| `pnpm` \| `yarn`\| `bun` | `npm` | -| `warnings` | Control Angular CLI specific console warnings. | [Warnings options](#warnings-options) | `{}` | +| Property | Details | Value type | Default value | +| :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------ | :------------ | +| `analytics` | Share anonymous usage data with the Angular Team. A boolean value indicates whether or not to share data, while a UUID string shares data using a pseudonymous identifier. | `boolean` \| `string` | `false` | +| `cache` | Control [persistent disk cache](cli/cache) used by [Angular CLI Builders](tools/cli/cli-builder). | [Cache options](#cache-options) | `{}` | +| `schematicCollections` | List schematics collections to use in `ng generate`. | `string[]` | `[]` | +| `packageManager` | The preferred package manager tool to use. | `npm` \| `cnpm` \| `pnpm` \| `yarn`\| `bun` | `npm` | +| `warnings` | Control Angular CLI specific console warnings. | [Warnings options](#warnings-options) | `{}` | ### Cache options -| Property | Details | Value type | Default value | -|:--- |:--- |:--- |:--- | -| `enabled` | Configure whether disk caching is enabled for builds. | `boolean` | `true` | -| `environment` | Configure in which environment disk cache is enabled.

    * `ci` enables caching only in continuous integration (CI) environments.
    * `local` enables caching only *outside* of CI environments.
    * `all` enables caching everywhere. | `local` \| `ci` \| `all` | `local` | -| `path` | The directory used to stored cache results. | `string` | `.angular/cache` | +| Property | Details | Value type | Default value | +| :------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------- | :--------------- | +| `enabled` | Configure whether disk caching is enabled for builds. | `boolean` | `true` | +| `environment` | Configure in which environment disk cache is enabled.

    _ `ci` enables caching only in continuous integration (CI) environments.
    _ `local` enables caching only _outside_ of CI environments.
    \* `all` enables caching everywhere. | `local` \| `ci` \| `all` | `local` | +| `path` | The directory used to stored cache results. | `string` | `.angular/cache` | ### Warnings options | Property | Details | Value type | Default value | -|:--- |:--- |:--- |:--- | +| :---------------- | :------------------------------------------------------------------------------ | :--------- | :------------ | | `versionMismatch` | Show a warning when the global Angular CLI version is newer than the local one. | `boolean` | `true` | ## Project configuration options @@ -61,7 +63,7 @@ The following properties are a set of options that customize the Angular CLI. The following top-level configuration properties are available for each project, under `projects['project-name']`. | Property | Details | Value type | Default value | -|:--- |:--- |:--- |:--- | +| :------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------- | :-------------- | | `root` | The root directory for this project's files, relative to the workspace directory. Empty for the initial application, which resides at the top level of the workspace. | `string` | None (required) | | `projectType` | One of "application" or "library" An application can run independently in a browser, while a library cannot. | `application` \| `library` | None (required) | | `sourceRoot` | The root directory for this project's source files. | `string` | `''` | @@ -81,8 +83,7 @@ For example, the schematic for generating a component with `ng generate componen The fields given in the schematic's schema correspond to the allowed command-line argument values and defaults for the Angular CLI sub-command options. You can update your workspace schema file to set a different default for a sub-command option. For example, to disable `standalone` in `ng generate component` by default: - - +```json { "projects": { "my-app": { @@ -94,8 +95,7 @@ You can update your workspace schema file to set a different default for a sub-c } } } - - +``` ## Configuring CLI builders @@ -121,7 +121,7 @@ Each target also has an `options` section that configures default options for th See the example in [Build target](#build-target) below. | Property | Details | -|:--- |:--- | +| :------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `build` | Configures defaults for options of the `ng build` command. See the [Build target](#build-target) section for more information. | | `serve` | Overrides build defaults and supplies extra serve defaults for the `ng serve` command. Besides the options available for the `ng build` command, it adds options related to serving the application. | | `e2e` | Overrides build defaults for building end-to-end testing applications using the `ng e2e` command. | @@ -135,22 +135,21 @@ HELPFUL: All options in the configuration file must use `camelCase`, rather than Each target under `architect` has the following properties: -| Property | Details | -|:--- |:--- | -| `builder` | The CLI builder used to create this target in the form of `:`. | -| `options` | Build target default options. | -| `configurations`| Alternative configurations for executing the target. Each configuration sets the default options for that intended environment, overriding the associated value under `options`. See [Alternate build configurations](#alternate-build-configurations) below. | +| Property | Details | +| :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `builder` | The CLI builder used to create this target in the form of `:`. | +| `options` | Build target default options. | +| `configurations` | Alternative configurations for executing the target. Each configuration sets the default options for that intended environment, overriding the associated value under `options`. See [Alternate build configurations](#alternate-build-configurations) below. | For example, to configure a build with optimizations disabled: - - +```json { "projects": { "my-app": { "architect": { "build": { - "builder": "@angular-devkit/build-angular:application", + "builder": "@angular/build:application", "options": { "optimization": false } @@ -159,32 +158,30 @@ For example, to configure a build with optimizations disabled: } } } - - +``` ### Alternate build configurations Angular CLI comes with two build configurations: `production` and `development`. By default, the `ng build` command uses the `production` configuration, which applies several build optimizations, including: -* Bundling files -* Minimizing excess whitespace -* Removing comments and dead code -* Minifying code to use short, mangled names +- Bundling files +- Minimizing excess whitespace +- Removing comments and dead code +- Minifying code to use short, mangled names You can define and name extra alternate configurations (such as `staging`, for instance) appropriate to your development process. You can select an alternate configuration by passing its name to the `--configuration` command line flag. For example, to configure a build where optimization is enabled only for production builds (`ng build --configuration production`): - - +```json { "projects": { "my-app": { "architect": { "build": { - "builder": "@angular-devkit/build-angular:application", + "builder": "@angular/build:application", "options": { "optimization": false }, @@ -198,8 +195,7 @@ For example, to configure a build where optimization is enabled only for product } } } - - +``` You can also pass in more than one configuration name as a comma-separated list. For example, to apply both `staging` and `french` build configurations, use the command `ng build --configuration staging,french`. @@ -209,18 +205,27 @@ In this example, if both `staging` and `french` configurations set the output pa ### Extra build and test options -The configurable options for a default or targeted build generally correspond to the options available for the [`ng build`](cli/build), [`ng serve`](cli/serve), and [`ng test`](cli/test) commands. +The configurable options for a default or targeted build generally correspond to the options available for the [`ng build`](cli/build), and [`ng test`](cli/test) commands. For details of those options and their possible values, see the [Angular CLI Reference](cli). | Options properties | Details | -|:--- |:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `assets` | An object containing paths to static assets to serve with the application. The default paths point to the project's `public` directory. See more in the [Assets configuration](#assets-configuration) section. | +| :------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `assets` | An object containing paths to static assets to serve with the application. The default paths point to the project's `public` directory. See more in the [Assets configuration](#assets-configuration) section. | | `styles` | An array of CSS files to add to the global context of the project. Angular CLI supports CSS imports and all major CSS preprocessors. See more in the [Styles and scripts configuration](#styles-and-scripts-configuration) section. | | `stylePreprocessorOptions` | An object containing option-value pairs to pass to style preprocessors. See more in the [Styles and scripts configuration](#styles-and-scripts-configuration) section. | | `scripts` | An object containing JavaScript files to add to the application. The scripts are loaded exactly as if you had added them in a ` diff --git a/adev-ja/src/content/reference/versions.md b/adev-ja/src/content/reference/versions.md index e91f82913c..0d07f46e16 100644 --- a/adev-ja/src/content/reference/versions.md +++ b/adev-ja/src/content/reference/versions.md @@ -1,7 +1,7 @@ # バヌゞョン互換性 -次の衚は、各バヌゞョンのAngularで必芁ずなる -Node.js、TypeScript、RxJSのバヌゞョンを瀺しおいたす。 +次の衚は、各バヌゞョンのAngularで必芁ずなるNode.js、TypeScript、RxJSの +バヌゞョンを瀺しおいたす。 ## アクティブにサポヌトされおいるバヌゞョン @@ -9,22 +9,23 @@ Node.js、TypeScript、RxJSのバヌゞョンを瀺しおいたす。 | Angular | Node.js | TypeScript | RxJS | | ------------------ | ----------------------------------- | -------------- | ------------------ | -| 20.2.x \|\| 20.3.x | ^20.19.0 \|\| ^22.12.0 \|\| ^24.0.0 | >=5.9.0 <6.0.0 | ^6.5.3 \|\| ^7.4.0 | +| 21.0.x | ^20.19.0 \|\| ^22.12.0 \|\| ^24.0.0 | >=5.9.0 <6.0.0 | ^6.5.3 \|\| ^7.4.0 | +| 20.2.x \|\| 20.3.x | ^20.19.0 \|\| ^22.12.0 \|\| ^24.0.0 | >=5.8.0 <6.0.0 | ^6.5.3 \|\| ^7.4.0 | | 20.0.x \|\| 20.1.x | ^20.19.0 \|\| ^22.12.0 \|\| ^24.0.0 | >=5.8.0 <5.9.0 | ^6.5.3 \|\| ^7.4.0 | | 19.2.x | ^18.19.1 \|\| ^20.11.1 \|\| ^22.0.0 | >=5.5.0 <5.9.0 | ^6.5.3 \|\| ^7.4.0 | | 19.1.x | ^18.19.1 \|\| ^20.11.1 \|\| ^22.0.0 | >=5.5.0 <5.8.0 | ^6.5.3 \|\| ^7.4.0 | | 19.0.x | ^18.19.1 \|\| ^20.11.1 \|\| ^22.0.0 | >=5.5.0 <5.7.0 | ^6.5.3 \|\| ^7.4.0 | -| 18.1.x \|\| 18.2.x | ^18.19.1 \|\| ^20.11.1 \|\| ^22.0.0 | >=5.4.0 <5.6.0 | ^6.5.3 \|\| ^7.4.0 | -| 18.0.x | ^18.19.1 \|\| ^20.11.1 \|\| ^22.0.0 | >=5.4.0 <5.5.0 | ^6.5.3 \|\| ^7.4.0 | ## サポヌトされおいない Angular バヌゞョン -この衚は、長期サポヌト (LTS) の察象倖ずなっおいるAngularのバヌゞョンを察象ずしおいたす。 -この情報は、各バヌゞョンがLTSを終了したずきに正しいものであり、それ以降の保蚌はありたせん。 +この衚は、長期サポヌト (LTS) の察象倖ずなっおいるAngularのバヌゞョンを察象ずしおいたす。この +情報は、各バヌゞョンがLTSを終了したずきに正しいものであり、それ以降の保蚌はありたせん。 過去の参照のためにここで蚘茉されおいたす。 | Angular | Node.js | TypeScript | RxJS | | ------------------ | ------------------------------------ | -------------- | ------------------ | +| 18.1.x \|\| 18.2.x | ^18.19.1 \|\| ^20.11.1 \|\| ^22.0.0 | >=5.4.0 <5.6.0 | ^6.5.3 \|\| ^7.4.0 | +| 18.0.x | ^18.19.1 \|\| ^20.11.1 \|\| ^22.0.0 | >=5.4.0 <5.5.0 | ^6.5.3 \|\| ^7.4.0 | | 17.3.x | ^18.13.0 \|\| ^20.9.0 | >=5.2.0 <5.5.0 | ^6.5.3 \|\| ^7.4.0 | | 17.1.x \|\| 17.2.x | ^18.13.0 \|\| ^20.9.0 | >=5.2.0 <5.4.0 | ^6.5.3 \|\| ^7.4.0 | | 17.0.x | ^18.13.0 \|\| ^20.9.0 | >=5.2.0 <5.3.0 | ^6.5.3 \|\| ^7.4.0 | @@ -68,23 +69,25 @@ Angular v9たで、AngularずAngular CLIのバヌゞョンは同期しおいた | 4.0.x \|\| 4.1.x | 1.0.x \|\| 1.1.x \|\| 1.2.x | ^6.9.0 | >=2.1.6 <2.4.0 | ^5.0.1 | | 2.x | - | ^6.9.0 | >=1.8.0 <2.2.0 | ^5.0.1 | -## ブラりザサポヌト +## ブラりザサポヌト {#browser-support} -Angular uses the ["widely available" Baseline](https://web.dev/baseline) to define browser -support. For each major version, Angular supports browsers included in the Baseline of a -chosen date near the release date for that major. +Angularは、ブラりザサポヌトを定矩するために["widely available" Baseline](https://web.dev/baseline)を䜿甚しおいたす。 +各メゞャヌバヌゞョンに぀いお、Angularはそのメゞャヌバヌゞョンのリリヌス日に近い遞択された日付のBaselineに含たれる +ブラりザをサポヌトしたす。 -The "widely available" Baseline includes browsers released less than 30 months (2.5 years) -of the chosen date within Baseline's core browser set (Chrome, Edge, Firefox, Safari) and -targets supporting approximately 95% of web users. +"widely available" Baselineには、BaselineのコアブラりザセットChrome、Edge、Firefox、Safari内で遞択された日付から30か月2.5幎未満にリリヌスされたブラりザが含たれ、 +箄95%のWebナヌザヌをサポヌトするこずを +目暙ずしおいたす。 | Angular | Baseline Date | Browser Set | | ------- | ------------- | --------------------------- | +| v21 | 2025-10-20 | [Browser Set][browsers-v21] | | v20 | 2025-04-30 | [Browser Set][browsers-v20] | +[browsers-v21]: https://web-platform-dx.github.io/web-features/supported-browsers/?widelyAvailableOnDate=2025-10-20&includeDownstream=false [browsers-v20]: https://web-platform-dx.github.io/web-features/supported-browsers/?widelyAvailableOnDate=2025-04-30&includeDownstream=false -Angular versions prior to v20 support the following specific browser versions: +v20より前のAngularバヌゞョンは、次の特定のブラりザバヌゞョンをサポヌトしおいたす: | ブラりザ | サポヌトされおいるバヌゞョン | | :------ | :------------------------------------------ | @@ -146,14 +149,14 @@ CLIを䜿甚しおいない堎合は、ホストWebペヌゞ`index.html` * これらのオプションは、開始パフォヌマンスを向䞊させるためだけに䜿甚しおください。 * 远跡が難しいバグが発生する可胜性があるため、どのような操䜜を行っおいるのかを理解しおいる堎合にのみ䜿甚しおください。 */ - // __Zone_disable_requestAnimationFrame = true; // requestAnimationFrame のパッチを無効にする - // __Zone_disable_on_property = true; // onclick などの onProperty のパッチを無効にする - // __zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // 指定したむベント名のパッチを無効にする + // __Zone_disable_requestAnimationFrame = true; // requestAnimationFrame のパッチを無効にする + // __Zone_disable_on_property = true; // onclick などの onProperty のパッチを無効にする + // __zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // 指定したむベント名のパッチを無効にする /* * Edge 開発者ツヌルでは、addEventListener も zone.js によっおラップされたす。 * 次のフラグを䜿甚するず、Edge に察する zone.js のパッチをバむパスできたす。 */ - // __Zone_enable_cross_context_check = true; + // __Zone_enable_cross_context_check = true; From 81a94fa76abb8b19c86ebe518a100ec17ed9d170 Mon Sep 17 00:00:00 2001 From: Suguru Inatomi Date: Thu, 20 Nov 2025 15:52:04 +0900 Subject: [PATCH 24/55] fix: migrate contents /tools/cli --- adev-ja/src/content/tools/cli/build.en.md | 57 +++++++++--------- adev-ja/src/content/tools/cli/build.md | 25 ++++---- .../src/content/tools/cli/deployment.en.md | 50 ++++++++-------- adev-ja/src/content/tools/cli/deployment.md | 42 +++++++------- adev-ja/src/content/tools/cli/serve.en.md | 58 +++++++------------ adev-ja/src/content/tools/cli/serve.md | 58 +++++++------------ .../src/content/tools/cli/setup-local.en.md | 46 +++++++++------ adev-ja/src/content/tools/cli/setup-local.md | 44 ++++++++------ 8 files changed, 185 insertions(+), 195 deletions(-) diff --git a/adev-ja/src/content/tools/cli/build.en.md b/adev-ja/src/content/tools/cli/build.en.md index 8f7367e5fb..a7507182ad 100644 --- a/adev-ja/src/content/tools/cli/build.en.md +++ b/adev-ja/src/content/tools/cli/build.en.md @@ -6,20 +6,19 @@ This will compile your TypeScript code to JavaScript, as well as optimize, bundl `ng build` only executes the builder for the `build` target in the default project as specified in `angular.json`. Angular CLI includes four builders typically used as `build` targets: -| Builder | Purpose | -| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `@angular-devkit/build-angular:application` | Builds an application with a client-side bundle, a Node server, and build-time prerendered routes with [esbuild](https://esbuild.github.io/). | +| Builder | Purpose | +| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `@angular-devkit/build-angular:application` | Builds an application with a client-side bundle, a Node server, and build-time prerendered routes with [esbuild](https://esbuild.github.io/). | | `@angular-devkit/build-angular:browser-esbuild` | Bundles a client-side application for use in a browser with [esbuild](https://esbuild.github.io/). See [`browser-esbuild` documentation](tools/cli/build-system-migration#manual-migration-to-the-compatibility-builder) for more information. | -| `@angular-devkit/build-angular:browser` | Bundles a client-side application for use in a browser with [webpack](https://webpack.js.org/). | -| `@angular-devkit/build-angular:ng-packagr` | Builds an Angular library adhering to [Angular Package Format](tools/libraries/angular-package-format). | +| `@angular-devkit/build-angular:browser` | Bundles a client-side application for use in a browser with [webpack](https://webpack.js.org/). | +| `@angular-devkit/build-angular:ng-packagr` | Builds an Angular library adhering to [Angular Package Format](tools/libraries/angular-package-format). | Applications generated by `ng new` use `@angular-devkit/build-angular:application` by default. Libraries generated by `ng generate library` use `@angular-devkit/build-angular:ng-packagr` by default. You can determine which builder is being used for a particular project by looking up the `build` target for that project. - - +```json { "projects": { "my-app": { @@ -36,8 +35,7 @@ You can determine which builder is being used for a particular project by lookin } } } - - +``` This page discusses usage and options of `@angular-devkit/build-angular:application`. @@ -52,8 +50,7 @@ The CLI lets you set size thresholds in your configuration to ensure that parts Define your size boundaries in the CLI configuration file, `angular.json`, in a `budgets` section for each [configured environment](tools/cli/environments). - - +```json { 
 "configurations": { @@ -69,8 +66,7 @@ Define your size boundaries in the CLI configuration file, `angular.json`, in a } } } - - +``` You can specify size budgets for the entire app, and for particular parts. Each budget entry configures a budget of a given type. @@ -87,17 +83,17 @@ When you configure a budget, the builder warns or reports an error when a given Each budget entry is a JSON object with the following properties: -| Property | Value | -| :------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Property | Value | +| :------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | type | The type of budget. One of:
    Value Details
    bundle The size of a specific bundle.
    initial The size of JavaScript and CSS needed for bootstrapping the application. Defaults to warning at 500kb and erroring at 1mb.
    allScript The size of all scripts.
    all The size of the entire application.
    anyComponentStyle This size of any one component stylesheet. Defaults to warning at 2kb and erroring at 4kb.
    anyScript The size of any one script.
    any The size of any file.
    | -| name | The name of the bundle (for `type=bundle`). | -| baseline | The baseline size for comparison. | -| maximumWarning | The maximum threshold for warning relative to the baseline. | -| maximumError | The maximum threshold for error relative to the baseline. | -| minimumWarning | The minimum threshold for warning relative to the baseline. | -| minimumError | The minimum threshold for error relative to the baseline. | -| warning | The threshold for warning relative to the baseline (min & max). | -| error | The threshold for error relative to the baseline (min & max). | +| name | The name of the bundle (for `type=bundle`). | +| baseline | The baseline size for comparison. | +| maximumWarning | The maximum threshold for warning relative to the baseline. | +| maximumError | The maximum threshold for error relative to the baseline. | +| minimumWarning | The minimum threshold for warning relative to the baseline. | +| minimumError | The minimum threshold for error relative to the baseline. | +| warning | The threshold for warning relative to the baseline (min & max). | +| error | The threshold for error relative to the baseline (min & max). | ## Configuring CommonJS dependencies @@ -112,8 +108,7 @@ Angular CLI outputs warnings if it detects that your browser application depends When you encounter a CommonJS dependency, consider asking the maintainer to support ECMAScript modules, contributing that support yourself, or using an alternative dependency which meets your needs. If the best option is to use a CommonJS dependency, you can disable these warnings by adding the CommonJS module name to `allowedCommonJsDependencies` option in the `build` options located in `angular.json`. - - +```json "build": { "builder": "@angular-devkit/build-angular:browser", "options": { @@ -124,8 +119,7 @@ If the best option is to use a CommonJS dependency, you can disable these warnin } 
 }, - - +``` ## Configuring browser compatibility @@ -146,4 +140,11 @@ HELPFUL: Use [browsersl.ist](https://browsersl.ist) to display compatible browse Angular supports [Tailwind CSS](https://tailwindcss.com/), a utility-first CSS framework. -To integrate Tailwind CSS with Angular CLI, see [Using Tailwind CSS with Angular](guide/tailwind) \ No newline at end of file +To integrate Tailwind CSS with Angular CLI, see [Using Tailwind CSS with Angular](guide/tailwind) + +## Critical CSS inlining + +Angular can inline the critical CSS definitions of your application to improve [First Contentful Paint (FCP)](https://web.dev/first-contentful-paint). +This option is enabled default. You can disable this inlining in the [`styles` customization options](reference/configs/workspace-config#styles-optimization-options). + +This optimization extracts the CSS needed to render the initial viewport and inlines it directly into the generated HTML, allowing the browser to display content faster without waiting for the full stylesheets to load. The remaining CSS then loads asynchronously in the background. Angular CLI uses [Beasties](https://github.com/danielroe/beasties) to analyze your application’s HTML and styles. diff --git a/adev-ja/src/content/tools/cli/build.md b/adev-ja/src/content/tools/cli/build.md index 6bdc6dd9aa..212832229c 100644 --- a/adev-ja/src/content/tools/cli/build.md +++ b/adev-ja/src/content/tools/cli/build.md @@ -18,8 +18,7 @@ Angular CLIには、通垞`build`タヌゲットずしお䜿甚される4぀の 特定のプロゞェクトで䜿甚されおいるビルダヌは、そのプロゞェクトの`build`タヌゲットを調べるこずで刀断できたす。 - - +```json { "projects": { "my-app": { @@ -36,8 +35,7 @@ Angular CLIには、通垞`build`タヌゲットずしお䜿甚される4぀の } } } - - +``` このペヌゞでは、`@angular-devkit/build-angular:application`の䜿甚法ずオプションに぀いお説明したす。 @@ -52,8 +50,7 @@ CLIを䜿甚するず、蚭定でサむズしきい倀を蚭定しお、アプ サむズ境界は、CLI蚭定ファむル`angular.json`の、各[蚭定枈み環境](tools/cli/environments)の`budgets`セクションで定矩したす。 - - +```json { 
 "configurations": { @@ -69,8 +66,7 @@ CLIを䜿甚するず、蚭定でサむズしきい倀を蚭定しお、アプ } } } - - +``` アプリケヌション党䜓および特定のパヌツに察しおサむズバゞェットを指定できたす。 各バゞェット゚ントリは、特定のタむプのバゞェットを蚭定したす。 @@ -112,8 +108,7 @@ Angular CLIは、ブラりザアプリケヌションがCommonJSモゞュヌル CommonJS䟝存関係に遭遇した堎合は、メンテナヌにECMAScriptモゞュヌルのサポヌトを䟝頌するか、自分でそのサポヌトに貢献するか、たたはニヌズを満たす代替の䟝存関係を䜿甚するこずを怜蚎しおください。 CommonJS䟝存関係を䜿甚するのが最善の遞択肢である堎合は、`angular.json`にある`build`オプションの`allowedCommonJsDependencies`オプションにCommonJSモゞュヌル名を远加するこずで、これらの譊告を無効にできたす。 - - +```json "build": { "builder": "@angular-devkit/build-angular:browser", "options": { @@ -124,8 +119,7 @@ CommonJS䟝存関係を䜿甚するのが最善の遞択肢である堎合は、 } 
 }, - - +``` ## ブラりザの互換性を蚭定する {#configuring-browser-compatibility} @@ -147,3 +141,10 @@ HELPFUL: [browsersl.ist](https://browsersl.ist)を䜿甚しお、`browserslist` Angularは[Tailwind CSS](https://tailwindcss.com/)、ナヌティリティファヌストのCSSフレヌムワヌクをサポヌトしおいたす。 Tailwind CSSをAngular CLIず統合するには、[AngularでのTailwind CSSの䜿甚](guide/tailwind)を参照しおください。 + +## クリティカルCSSのむンラむン化 {#critical-css-inlining} + +Angularは、[First Contentful Paint (FCP)](https://web.dev/first-contentful-paint)を改善するために、アプリケヌションのクリティカルCSS定矩をむンラむン化できたす。 +このオプションはデフォルトで有効になっおいたす。[`styles`カスタマむズオプション](reference/configs/workspace-config#styles-optimization-options)でこのむンラむン化を無効にできたす。 + +この最適化は、初期ビュヌポヌトのレンダリングに必芁なCSSを抜出し、生成されたHTMLに盎接むンラむン化したす。これにより、ブラりザは完党なスタむルシヌトの読み蟌みを埅たずに、より高速にコンテンツを衚瀺できたす。残りのCSSはバックグラりンドで非同期に読み蟌たれたす。Angular CLIは、アプリケヌションのHTMLずスタむルを分析するために[Beasties](https://github.com/danielroe/beasties)を䜿甚したす。 diff --git a/adev-ja/src/content/tools/cli/deployment.en.md b/adev-ja/src/content/tools/cli/deployment.en.md index d69b3e1b8e..bed7aceb79 100644 --- a/adev-ja/src/content/tools/cli/deployment.en.md +++ b/adev-ja/src/content/tools/cli/deployment.en.md @@ -13,12 +13,12 @@ You can then use the `ng deploy` command to deploy that project. For example, the following command automatically deploys a project to [Firebase](https://firebase.google.com/). - +```shell ng add @angular/fire ng deploy - +``` The command is interactive. In this case, you must have or create a Firebase account and authenticate using it. @@ -28,10 +28,10 @@ The table below lists tools which implement deployment functionality to differen The `deploy` command for each package may require different command line options. You can read more by following the links associated with the package names below: -| Deployment to | Setup Command | -|:--- |:--- | +| Deployment to | Setup Command | +| :---------------------------------------------------------------- | :------------------------------------------------------------------------------------------ | | [Firebase hosting](https://firebase.google.com/docs/hosting) | [`ng add @angular/fire`](https://npmjs.org/package/@angular/fire) | -| [Vercel](https://vercel.com/solutions/angular) | [`vercel init angular`](https://github.com/vercel/vercel/tree/main/examples/angular) | +| [Vercel](https://vercel.com/solutions/angular) | [`vercel init angular`](https://github.com/vercel/vercel/tree/main/examples/angular) | | [Netlify](https://www.netlify.com) | [`ng add @netlify-builder/deploy`](https://npmjs.org/package/@netlify-builder/deploy) | | [GitHub pages](https://pages.github.com) | [`ng add angular-cli-ghpages`](https://npmjs.org/package/angular-cli-ghpages) | | [Amazon Cloud S3](https://aws.amazon.com/s3/?nc2=h_ql_prod_st_s3) | [`ng add @jefiozie/ngx-aws-deploy`](https://www.npmjs.com/package/@jefiozie/ngx-aws-deploy) | @@ -60,17 +60,17 @@ Client-side rendered Angular applications are perfect candidates for serving wit If the application uses the Angular router, you must configure the server to return the application's host page (`index.html`) when asked for a file that it does not have. A routed application should support "deep links". -A *deep link* is a URL that specifies a path to a component inside the application. -For example, `http://my-app.test/users/42` is a *deep link* to the user detail page that displays the user with `id` 42. +A _deep link_ is a URL that specifies a path to a component inside the application. +For example, `http://my-app.test/users/42` is a _deep link_ to the user detail page that displays the user with `id` 42. There is no issue when the user initially loads the index page and then navigates to that URL from within a running client. -The Angular router performs the navigation *client-side* and does not request a new HTML page. +The Angular router performs the navigation _client-side_ and does not request a new HTML page. -But clicking a deep link in an email, entering it in the browser address bar, or even refreshing the browser while already on the deep linked page will all be handled by the browser itself, *outside* the running application. +But clicking a deep link in an email, entering it in the browser address bar, or even refreshing the browser while already on the deep linked page will all be handled by the browser itself, _outside_ the running application. The browser makes a direct request to the server for `/users/42`, bypassing Angular's router. A static server routinely returns `index.html` when it receives a request for `http://my-app.test/`. -But most servers by default will reject `http://my-app.test/users/42` and returns a `404 - Not Found` error *unless* it is configured to return `index.html` instead. +But most servers by default will reject `http://my-app.test/users/42` and returns a `404 - Not Found` error _unless_ it is configured to return `index.html` instead. Configure the fallback route or 404 page to `index.html` for your server, so Angular is served for deep links and can display the correct route. Some servers call this fallback behavior "Single-Page Application" (SPA) mode. @@ -81,25 +81,25 @@ For "real" 404 pages such as `http://my-app.test/does-not-exist`, the server doe ### Requesting data from a different server (CORS) -Web developers may encounter a [*cross-origin resource sharing*](https://developer.mozilla.org/docs/Web/HTTP/CORS "Cross-origin resource sharing") error when making a network request to a server other than the application's own host server. +Web developers may encounter a [_cross-origin resource sharing_](https://developer.mozilla.org/docs/Web/HTTP/CORS 'Cross-origin resource sharing') error when making a network request to a server other than the application's own host server. Browsers forbid such requests unless the server explicitly permits them. There isn't anything Angular or the client application can do about these errors. The _server_ must be configured to accept the application's requests. -Read about how to enable CORS for specific servers at [enable-cors.org](https://enable-cors.org/server.html "Enabling CORS server"). +Read about how to enable CORS for specific servers at [enable-cors.org](https://enable-cors.org/server.html 'Enabling CORS server'). ## Production optimizations `ng build` uses the `production` configuration unless configured otherwise. This configuration enables the following build optimization features. -| Features | Details | -|:--- |:--- | -| [Ahead-of-Time (AOT) Compilation](tools/cli/aot-compiler) | Pre-compiles Angular component templates. | +| Features | Details | +| :---------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- | +| [Ahead-of-Time (AOT) Compilation](tools/cli/aot-compiler) | Pre-compiles Angular component templates. | | [Production mode](tools/cli/deployment#development-only-features) | Optimizes the application for the best runtime performance | -| Bundling | Concatenates your many application and library files into a minimum number of deployed files. | -| Minification | Removes excess whitespace, comments, and optional tokens. | -| Mangling | Renames functions, classes, and variables to use shorter, arbitrary identifiers. | -| Dead code elimination | Removes unreferenced modules and unused code. | +| Bundling | Concatenates your many application and library files into a minimum number of deployed files. | +| Minification | Removes excess whitespace, comments, and optional tokens. | +| Mangling | Renames functions, classes, and variables to use shorter, arbitrary identifiers. | +| Dead code elimination | Removes unreferenced modules and unused code. | See [`ng build`](cli/build) for more about CLI build options and their effects. @@ -108,9 +108,9 @@ See [`ng build`](cli/build) for more about CLI build options and their effects. When you run an application locally using `ng serve`, Angular uses the development configuration at runtime which enables: -* Extra safety checks such as [`expression-changed-after-checked`](errors/NG0100) detection. -* More detailed error messages. -* Additional debugging utilities such as the global `ng` variable with [debugging functions](api#core-global) and [Angular DevTools](tools/devtools) support. +- Extra safety checks such as [`expression-changed-after-checked`](errors/NG0100) detection. +- More detailed error messages. +- Additional debugging utilities such as the global `ng` variable with [debugging functions](api#core-global) and [Angular DevTools](tools/devtools) support. These features are helpful during development, but they require extra code in the app, which is undesirable in production. To ensure these features do not negatively impact bundle size for end users, Angular CLI @@ -120,13 +120,13 @@ Building your application with `ng build` by default uses the `production` confi ## `--deploy-url` -`--deploy-url` is a command line option used to specify the base path for resolving relative URLs for assets such as images, scripts, and style sheets at *compile* time. +`--deploy-url` is a command line option used to specify the base path for resolving relative URLs for assets such as images, scripts, and style sheets at _compile_ time. - +```shell ng build --deploy-url /my/assets - +``` The effect and purpose of `--deploy-url` overlaps with [``](guide/routing/common-router-tasks). Both can be used for initial scripts, stylesheets, lazy scripts, and css resources. diff --git a/adev-ja/src/content/tools/cli/deployment.md b/adev-ja/src/content/tools/cli/deployment.md index d7e202ea7b..bc3d61d3f8 100644 --- a/adev-ja/src/content/tools/cli/deployment.md +++ b/adev-ja/src/content/tools/cli/deployment.md @@ -13,12 +13,12 @@ AngularのCLIコマンドである`ng deploy`はあなたのプロゞェクト 䟋えば、以䞋のコマンドは[Firebase](https://firebase.google.com/)にプロゞェクトを自動的にデプロむできたす。 - +```shell ng add @angular/fire ng deploy - +``` コマンドは察話的です。 このケヌスでは、Firebaseアカりントを持っおいるか䜜成しなくおはならず、それを䜿甚しお認蚌しなくおはなりたせん。 @@ -28,10 +28,10 @@ ng deploy 各パッケヌゞの`deploy`コマンドは異なるコマンドラむンオプションを芁求したす。 以䞋のパッケヌゞ名に関連付けられたリンクをたどるこずで、より詳现を読むこずができたす。 -| デプロむ先 | セットアップコマンド | -|:--- |:--- | +| デプロむ先 | セットアップコマンド | +| :---------------------------------------------------------------- | :------------------------------------------------------------------------------------------ | | [Firebase hosting](https://firebase.google.com/docs/hosting) | [`ng add @angular/fire`](https://npmjs.org/package/@angular/fire) | -| [Vercel](https://vercel.com/solutions/angular) | [`vercel init angular`](https://github.com/vercel/vercel/tree/main/examples/angular) | +| [Vercel](https://vercel.com/solutions/angular) | [`vercel init angular`](https://github.com/vercel/vercel/tree/main/examples/angular) | | [Netlify](https://www.netlify.com) | [`ng add @netlify-builder/deploy`](https://npmjs.org/package/@netlify-builder/deploy) | | [GitHub pages](https://pages.github.com) | [`ng add angular-cli-ghpages`](https://npmjs.org/package/angular-cli-ghpages) | | [Amazon Cloud S3](https://aws.amazon.com/s3/?nc2=h_ql_prod_st_s3) | [`ng add @jefiozie/ngx-aws-deploy`](https://www.npmjs.com/package/@jefiozie/ngx-aws-deploy) | @@ -60,17 +60,17 @@ ng deploy もしアプリケヌションがAngularのルヌタヌを䜿っおいるならば、持っおいないファむルを芁求した時、アプリケヌションのホストペヌゞ(`index.html`)を返すよう蚭定しなければなりたせん。 ルヌティングされたアプリケヌションは「ディヌプリンク」をサポヌトするべきです。 -*ディヌプリンク*はアプリケヌションの䞭のコンポヌネントぞの経路を指定したURLです。 -䟋えば、`http://my-app.test/users/42`は`id`42のナヌザヌを衚瀺するナヌザヌ詳现ペヌゞぞの*ディヌプリンク*です。 +_ディヌプリンク_はアプリケヌションの䞭のコンポヌネントぞの経路を指定したURLです。 +䟋えば、`http://my-app.test/users/42`は`id`42のナヌザヌを衚瀺するナヌザヌ詳现ペヌゞぞの_ディヌプリンク_です。 ナヌザヌが最初にindexペヌゞをロヌドし、それから起動䞭のクラむアント内からそのURLに移動するのは問題ありたせん。 -Angularのルヌタヌは*クラむアントサむド*でナビゲヌションを実行し、新しいHTMLを芁求したせん。 +Angularのルヌタヌは_クラむアントサむド_でナビゲヌションを実行し、新しいHTMLを芁求したせん。 -しかし、電子メヌル内のディヌプリンクをクリックしたり、ブラりザのアドレスバヌにディヌプリンクを入力したり、既にディヌプリンクに玐づけられたペヌゞをブラりザでリフレッシュするずきさえも、実行しおいるアプリケヌションの*倖郚*ですべおブラりザ自身によっお凊理されたす。 +しかし、電子メヌル内のディヌプリンクをクリックしたり、ブラりザのアドレスバヌにディヌプリンクを入力したり、既にディヌプリンクに玐づけられたペヌゞをブラりザでリフレッシュするずきさえも、実行しおいるアプリケヌションの_倖郚_ですべおブラりザ自身によっお凊理されたす。 Angularのルヌタヌを迂回しお、ブラりザは`/users/42`に察するサヌバヌぞの盎接のリク゚ストを䜜成したす。 静的なサヌバヌは`http://my-app.test/`に察するリク゚ストを受け取るず決たっお`index.html`を返したす。 -しかし、デフォルトでほずんどサヌバヌは`index.html`を代わりに返すよう蚭定されお*いないかぎり*`http://my-app.test/users/42`を拒吊しお`404 - Not Found`゚ラヌを返したす。 +しかし、デフォルトでほずんどサヌバヌは`index.html`を代わりに返すよう蚭定されお_いないかぎり_`http://my-app.test/users/42`を拒吊しお`404 - Not Found`゚ラヌを返したす。 フォヌルバックルヌトを蚭定するか、サヌバヌ䞊で404ペヌゞを`index.html`にする蚭定するこずで、Angularはディヌプリンクに関するサヌビスを提䟛し、正しいルヌトを衚瀺できたす。 いく぀かのサヌバヌはこのフォヌルバックの挙動を"Single-Page Application"(SPA)モヌドず呌びたす。 @@ -81,20 +81,20 @@ Angularのルヌタヌを迂回しお、ブラりザは`/users/42`に察する ### 異なるサヌバヌからデヌタをリク゚ストする(CORS) -アプリケヌション自身のホストサヌバヌ以倖のサヌバヌにネットワヌクリク゚ストを行う際、Web開発者は[*クロスオリゞンリ゜ヌス共有*](https://developer.mozilla.org/docs/Web/HTTP/CORS "クロスオリゞンリ゜ヌス共有")゚ラヌに遭遇するかもしれたせん。 +アプリケヌション自身のホストサヌバヌ以倖のサヌバヌにネットワヌクリク゚ストを行う際、Web開発者は[_クロスオリゞンリ゜ヌス共有_](https://developer.mozilla.org/docs/Web/HTTP/CORS 'クロスオリゞンリ゜ヌス共有')゚ラヌに遭遇するかもしれたせん。 ブラりザはサヌバヌが明瀺的に蚱可しおいない限りそのようなリク゚ストを犁止したす。 これらの゚ラヌに関しおAngularたたはクラむアントアプリケヌションでできるこずは䜕もありたせん。 -*サヌバヌ*はアプリケヌションのリク゚ストを受け付けるよう蚭定されおいなければなりたせん。 -特定のサヌバヌでCORSを有効にする方法は[enable-cors.org](https://enable-cors.org/server.html "CORSサヌバヌの有効化")を読んでください。 +_サヌバヌ_はアプリケヌションのリク゚ストを受け付けるよう蚭定されおいなければなりたせん。 +特定のサヌバヌでCORSを有効にする方法は[enable-cors.org](https://enable-cors.org/server.html 'CORSサヌバヌの有効化')を読んでください。 ## プロダクションの最適化 `ng build`は特に蚭定しない限り`production`蚭定を䜿いたす。この蚭定はビルド最適化機胜を有効にしたす。 | 機胜 | 詳现 | -|:--- |:--- | -| [事前(AOT)コンパむル](guide/aot-compiler) | Angularコンポヌネントのテンプレヌトの事前コンパむル。 | +| :-------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- | +| [事前(AOT)コンパむル](tools/cli/aot-compiler) | Angularコンポヌネントのテンプレヌトの事前コンパむル。 | | [プロダクションモヌド](tools/cli/deployment#development-only-features)| 実行時のパフォヌマンスを最高にするためのアプリケヌションの最適化 | | バンドル | 倚数のアプリケヌションおよびラむブラリを連結しおデプロむされるファむルを最小限の数にする。 | | 最小化 | 䜙分なホワむトスペヌス、コメントおよびオプショナルなトヌクンを取り陀く。 | @@ -108,9 +108,9 @@ CLIのビルドオプションずそれらの効果に぀いおより倚く知 `ng serve`を䜿っおロヌカルでアプリケヌションを起動するずき、Angularは開発甚の蚭定を䜿甚するこずで、 実行時に以䞋が䜿甚可胜になりたす: -* [`expression-changed-after-checked`](errors/NG0100)の怜出のような安党な远加のチェック。 -* より詳现な゚ラヌメッセヌゞ。 -* [デバッグ関数](api#core-global)および[Angular DevTools](tools/devtools)をサポヌトするグロヌバルな`ng`倉数のような远加のデバッグナヌティリティ。 +- [`expression-changed-after-checked`](errors/NG0100)の怜出のような安党な远加のチェック。 +- より詳现な゚ラヌメッセヌゞ。 +- [デバッグ関数](api#core-global)および[Angular DevTools](tools/devtools)をサポヌトするグロヌバルな`ng`倉数のような远加のデバッグナヌティリティ。 これらの機胜は開発䞭は䟿利ですが、アプリケヌションに远加のコヌドが必芁で、プロダクションでは望たれたせん。 ゚ンドナヌザヌのためのバンドルサむズにネガティブな圱響を䞎えないよう、これらの機胜を安党に䜿うために、Angular CLIは @@ -120,13 +120,13 @@ CLIのビルドオプションずそれらの効果に぀いおより倚く知 ## `--deploy-url` -`--deploy-url`は画像、スクリプト、スタむルシヌトずいった資材のための関連するURLを解決するためのベヌスずなるパスを*コンパむル*時に指定するのに䜿われるコマンドラむンオプションです。 +`--deploy-url`は画像、スクリプト、スタむルシヌトずいった資材のための関連するURLを解決するためのベヌスずなるパスを_コンパむル_時に指定するのに䜿われるコマンドラむンオプションです。 - +```shell ng build --deploy-url /my/assets - +``` `--deploy-url`の効果ず目的は[``](guide/routing/common-router-tasks)ず重なりたす。䞡者ずも初期のスクリプト、スタむルシヌト、遅延しお読み蟌たれるスクリプト、cssリ゜ヌスのために䜿甚できたす。 diff --git a/adev-ja/src/content/tools/cli/serve.en.md b/adev-ja/src/content/tools/cli/serve.en.md index 448b952e15..fe6761cb57 100644 --- a/adev-ja/src/content/tools/cli/serve.en.md +++ b/adev-ja/src/content/tools/cli/serve.en.md @@ -9,7 +9,7 @@ While any builder can be used here, the most common (and default) builder is `@a You can determine which builder is being used for a particular project by looking up the `serve` target for that project. - +```json { "projects": { @@ -27,7 +27,7 @@ You can determine which builder is being used for a particular project by lookin } } - +``` This page discusses usage and options of `@angular-devkit/build-angular:dev-server`. @@ -39,37 +39,34 @@ For example, to divert all calls for `http://localhost:4200/api` to a server run 1. Create a file `proxy.conf.json` in your project's `src/` folder. 1. Add the following content to the new proxy file: - - - { - "/api": { - "target": "http://localhost:3000", - "secure": false - } - } - - +```json +{ + "/api": { + "target": "http://localhost:3000", + "secure": false + } +} +``` 1. In the CLI configuration file, `angular.json`, add the `proxyConfig` option to the `serve` target: - - - { - "projects": { - "my-app": { - "architect": { - "serve": { - "builder": "@angular-devkit/build-angular:dev-server", - "options": { - "proxyConfig": "src/proxy.conf.json" - } +```json +{ + "projects": { + "my-app": { + "architect": { + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "proxyConfig": "src/proxy.conf.json" } - } } } } + } +} - +``` 1. To run the development server with this proxy configuration, call `ng serve`. @@ -77,14 +74,3 @@ Edit the proxy configuration file to add configuration options; following are so For a detailed description of all options, refer to the [webpack DevServer documentation](https://webpack.js.org/configuration/dev-server/#devserverproxy) when using `@angular-devkit/build-angular:browser`, or the [Vite DevServer documentation](https://vite.dev/config/server-options#server-proxy) when using `@angular-devkit/build-angular:browser-esbuild` or `@angular-devkit/build-angular:application`. NOTE: If you edit the proxy configuration file, you must relaunch the `ng serve` process to make your changes effective. - -## `localhost` resolution - -As of Node version 17, Node will _not_ always resolve `http://localhost:` to `http://127.0.0.1:` -depending on each machine's configuration. - -If you get an `ECONNREFUSED` error using a proxy targeting a `localhost` URL, -you can fix this issue by updating the target from `http://localhost:` to `http://127.0.0.1:`. - -See [the `http-proxy-middleware` documentation](https://github.com/chimurai/http-proxy-middleware#nodejs-17-econnrefused-issue-with-ipv6-and-localhost-705) -for more information. diff --git a/adev-ja/src/content/tools/cli/serve.md b/adev-ja/src/content/tools/cli/serve.md index 5dc57d36a2..ff28731504 100644 --- a/adev-ja/src/content/tools/cli/serve.md +++ b/adev-ja/src/content/tools/cli/serve.md @@ -9,7 +9,7 @@ Angular CLIアプリケヌションは、`ng serve`コマンドで配信でき 特定のプロゞェクトで䜿甚されおいるビルダヌは、そのプロゞェクトの`serve`タヌゲットを調べるこずで刀断できたす。 - +```json { "projects": { @@ -27,7 +27,7 @@ Angular CLIアプリケヌションは、`ng serve`コマンドで配信でき } } - +``` このペヌゞでは、`@angular-devkit/build-angular:dev-server`の䜿甚法ずオプションに぀いお説明したす。 @@ -39,37 +39,34 @@ Angular CLIアプリケヌションは、`ng serve`コマンドで配信でき 1. プロゞェクトの`src/`フォルダヌに`proxy.conf.json`ファむルを䜜成したす。 1. 新しいプロキシファむルに以䞋の内容を远加したす。 - - - { - "/api": { - "target": "http://localhost:3000", - "secure": false - } - } - - +```json +{ + "/api": { + "target": "http://localhost:3000", + "secure": false + } +} +``` 1. CLI蚭定ファむル`angular.json`で、`serve`タヌゲットに`proxyConfig`オプションを远加したす。 - - - { - "projects": { - "my-app": { - "architect": { - "serve": { - "builder": "@angular-devkit/build-angular:dev-server", - "options": { - "proxyConfig": "src/proxy.conf.json" - } +```json +{ + "projects": { + "my-app": { + "architect": { + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "proxyConfig": "src/proxy.conf.json" } - } } } } + } +} - +``` 1. このプロキシ蚭定で開発サヌバヌを実行するには、`ng serve`を呌び出したす。 @@ -77,14 +74,3 @@ Angular CLIアプリケヌションは、`ng serve`コマンドで配信でき すべおのオプションの詳现に぀いおは、`@angular-devkit/build-angular:browser`を䜿甚する堎合は[webpack DevServerドキュメント](https://webpack.js.org/configuration/dev-server/#devserverproxy)を、たたは`@angular-devkit/build-angular:browser-esbuild`たたは`@angular-devkit/build-angular:application`を䜿甚する堎合は[Vite DevServerドキュメント](https://vite.dev/config/server-options#server-proxy)を参照しおください。 NOTE: プロキシ蚭定ファむルを線集した堎合、倉曎を有効にするには`ng serve`プロセスを再起動する必芁がありたす。 - -## `localhost`の解決 {#localhost-resolution} - -Nodeバヌゞョン17以降、Nodeは`http://localhost:`を`http://127.0.0.1:`に垞に解決するずは限りたせん -これは各マシンの蚭定に䟝存したす。 - -もし`localhost`URLをタヌゲットずするプロキシを䜿甚しおいる際に`ECONNREFUSED`゚ラヌが発生した堎合、 -タヌゲットを`http://localhost:`から`http://127.0.0.1:`に曎新するこずで、この問題を解決できたす。 - -[`http-proxy-middleware`のドキュメント`](https://github.com/chimurai/http-proxy-middleware#nodejs-17-econnrefused-issue-with-ipv6-and-localhost-705)を参照しおください。 -詳现に぀いおは。 diff --git a/adev-ja/src/content/tools/cli/setup-local.en.md b/adev-ja/src/content/tools/cli/setup-local.en.md index 87a87af9f5..58ce7fdbb7 100644 --- a/adev-ja/src/content/tools/cli/setup-local.en.md +++ b/adev-ja/src/content/tools/cli/setup-local.en.md @@ -1,6 +1,6 @@ # Setting up the local environment and workspace -This guide explains how to set up your environment for Angular development using the [Angular CLI](cli "CLI command reference"). +This guide explains how to set up your environment for Angular development using the [Angular CLI](cli 'CLI command reference'). It includes information about installing the CLI, creating an initial workspace and starter app, and running that app locally to verify your setup. @@ -16,9 +16,9 @@ You don't need to set up your local environment until you're ready. To use Angular CLI, you should be familiar with the following: - - - + + + You should also be familiar with usage of command line interface (CLI) tools and have a general understanding of command shells. @@ -40,21 +40,25 @@ To install the Angular CLI, open a terminal window and run the following command npm install -g @angular/cli pnpm install -g @angular/cli yarn global add @angular/cli bun install -g @angular/cli @@ -66,37 +70,41 @@ To install the Angular CLI, open a terminal window and run the following command On Windows client computers, the execution of PowerShell scripts is disabled by default, so the above command may fail with an error. To allow the execution of PowerShell scripts, which is needed for npm global binaries, you must set the following execution policy: - +```sh Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned - +``` Carefully read the message displayed after executing the command and follow the instructions. Make sure you understand the implications of setting an execution policy. ### Unix permissions -On some Unix-like setups, global scripts may be owned by the root user, so to the above command may fail with a permission error. +On some Unix-like setups, global scripts may be owned by the root user, so to the above command may fail with a permission error. Run with `sudo` to execute the command as the root user and enter your password when prompted: sudo npm install -g @angular/cli sudo pnpm install -g @angular/cli sudo yarn global add @angular/cli sudo bun install -g @angular/cli @@ -111,11 +119,11 @@ You develop apps in the context of an Angular **workspace**. To create a new workspace and initial starter app, run the CLI command `ng new` and provide the name `my-app`, as shown here, then answer prompts about features to include: - +```shell ng new my-app - +``` The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a few minutes. @@ -123,21 +131,21 @@ This can take a few minutes. The CLI creates a new workspace and a small welcome app in a new directory with the same name as the workspace, ready to run. Navigate to the new directory so subsequent commands use this workspace. - +```shell cd my-app - +``` ## Run the application The Angular CLI includes a development server, for you to build and serve your app locally. Run the following command: - +```shell ng serve --open - +``` The `ng serve` command launches the server, watches your files, as well as rebuilds the app and reloads the browser as you make changes to those files. @@ -156,16 +164,16 @@ Each application has a `src` folder that contains its components, data, and asse You can edit the generated files directly, or add to and modify them using CLI commands. Use the [`ng generate`](cli/generate) command to add new files for additional components, directives, pipes, services, and more. Commands such as [`ng add`](cli/add) and [`ng generate`](cli/generate), which create or operate on applications and libraries, must be executed -from within a workspace. By contrast, commands such as `ng new` must be executed *outside* a workspace because they will create a new one. +from within a workspace. By contrast, commands such as `ng new` must be executed _outside_ a workspace because they will create a new one. ## Next steps -* Learn more about the [file structure](reference/configs/file-structure) and [configuration](reference/configs/workspace-config) of the generated workspace. +- Learn more about the [file structure](reference/configs/file-structure) and [configuration](reference/configs/workspace-config) of the generated workspace. -* Test your new application with [`ng test`](cli/test). +- Test your new application with [`ng test`](cli/test). -* Generate boilerplate like components, directives, and pipes with [`ng generate`](cli/generate). +- Generate boilerplate like components, directives, and pipes with [`ng generate`](cli/generate). -* Deploy your new application and make it available to real users with [`ng deploy`](cli/deploy). +- Deploy your new application and make it available to real users with [`ng deploy`](cli/deploy). -* Set up and run end-to-end tests of your application with [`ng e2e`](cli/e2e). +- Set up and run end-to-end tests of your application with [`ng e2e`](cli/e2e). diff --git a/adev-ja/src/content/tools/cli/setup-local.md b/adev-ja/src/content/tools/cli/setup-local.md index 4ff2d30ea2..dcf9eaa0a2 100644 --- a/adev-ja/src/content/tools/cli/setup-local.md +++ b/adev-ja/src/content/tools/cli/setup-local.md @@ -1,6 +1,6 @@ # ロヌカル環境ずワヌクスペヌスのセットアップ -このガむドでは、[Angular CLI](cli "CLIコマンドリファレンス")を䜿甚しおAngular開発環境をセットアップする方法を説明したす。 +このガむドでは、[Angular CLI](cli 'CLIコマンドリファレンス')を䜿甚しおAngular開発環境をセットアップする方法を説明したす。 これには、CLIのむンストヌル、初期ワヌクスペヌスずスタヌタヌアプリケヌションの䜜成、およびセットアップを確認するためにそのアプリケヌションをロヌカルで実行する方法に関する情報が含たれおいたす。 @@ -16,9 +16,9 @@ Angularを初めお䜿甚する堎合は、ブラりザでAngularの基本を玹 Angular CLIを䜿甚するには、以䞋の知識が必芁です。 - - - + + + たた、コマンドラむンむンタヌフェヌス(CLI)ツヌルの䜿甚法に粟通し、コマンドシェルに぀いお䞀般的な理解がある必芁がありたす。 @@ -40,21 +40,25 @@ Angular CLIをむンストヌルするには、タヌミナルりィンドりを npm install -g @angular/cli pnpm install -g @angular/cli yarn global add @angular/cli bun install -g @angular/cli @@ -66,11 +70,11 @@ Angular CLIをむンストヌルするには、タヌミナルりィンドりを Windowsクラむアントコンピュヌタヌでは、PowerShellスクリプトの実行はデフォルトで無効になっおいるため、䞊蚘のコマンドぱラヌで倱敗する可胜性がありたす。 npmグロヌバルバむナリに必芁なPowerShellスクリプトの実行を蚱可するには、次の実行ポリシヌを蚭定する必芁がありたす。 - +```sh Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned - +``` コマンド実行埌に衚瀺されるメッセヌゞを泚意深く読み、指瀺に埓っおください。実行ポリシヌを蚭定するこずの意味を理解しおいるこずを確認しおください。 @@ -82,21 +86,25 @@ rootナヌザヌずしおコマンドを実行するには`sudo`を付けお実 sudo npm install -g @angular/cli sudo pnpm install -g @angular/cli sudo yarn global add @angular/cli sudo bun install -g @angular/cli @@ -111,11 +119,11 @@ Angular**ワヌクスペヌス**のコンテキストでアプリケヌション 新しいワヌクスペヌスず初期スタヌタヌアプリケヌションを䜜成するには、CLIコマンド`ng new`を実行し、ここに瀺されおいるように`my-app`ずいう名前を指定しおから、含める機胜に関するプロンプトに回答したす。 - +```shell ng new my-app - +``` Angular CLIは、必芁なAngular npmパッケヌゞずその他の䟝存関係をむンストヌルしたす。 これには数分かかる堎合がありたす。 @@ -123,21 +131,21 @@ Angular CLIは、必芁なAngular npmパッケヌゞずその他の䟝存関係 CLIは、新しいワヌクスペヌスず、ワヌクスペヌスず同じ名前の新しいディレクトリに小さなりェルカムアプリケヌションを䜜成し、すぐに実行できる状態にしたす。 埌続のコマンドがこのワヌクスペヌスを䜿甚するように、新しいディレクトリに移動したす。 - +```shell cd my-app - +``` ## アプリケヌションを実行する {#run-the-application} Angular CLIには開発サヌバヌが含たれおおり、アプリケヌションをロヌカルでビルドしお提䟛できたす。次のコマンドを実行しおください。 - +```shell ng serve --open - +``` `ng serve`コマンドはサヌバヌを起動し、ファむルを監芖し、それらのファむルに倉曎を加えるずアプリケヌションを再ビルドしおブラりザをリロヌドしたす。 @@ -156,16 +164,16 @@ ng serve --open 生成されたファむルを盎接線集したり、CLIコマンドを䜿甚しお远加および倉曎したりできたす。 [`ng generate`](cli/generate)コマンドを䜿甚しお、远加のコンポヌネント、ディレクティブ、パむプ、サヌビスなどの新しいファむルを远加したす。 [`ng add`](cli/add)や[`ng generate`](cli/generate)のようなコマンドは、アプリケヌションやラむブラリを䜜成たたは操䜜するため、実行する必芁がありたす -ワヌクスペヌス内から。察照的に、`ng new`のようなコマンドは、新しいワヌクスペヌスを䜜成するため、ワヌクスペヌスの*倖*で実行する必芁がありたす。 +ワヌクスペヌス内から。察照的に、`ng new`のようなコマンドは、新しいワヌクスペヌスを䜜成するため、ワヌクスペヌスの_倖_で実行する必芁がありたす。 ## 次のステップ {#next-steps} -* 生成されたワヌクスペヌスの[ファむル構造](reference/configs/file-structure)ず[蚭定](reference/configs/workspace-config)に぀いおさらに孊びたしょう。 +- 生成されたワヌクスペヌスの[ファむル構造](reference/configs/file-structure)ず[蚭定](reference/configs/workspace-config)に぀いおさらに孊びたしょう。 -* [`ng test`](cli/test)で新しいアプリケヌションをテストしたしょう。 +- [`ng test`](cli/test)で新しいアプリケヌションをテストしたしょう。 -* コンポヌネント、ディレクティブ、パむプなどのボむラヌプレヌトを[`ng generate`](cli/generate)で生成したしょう。 +- コンポヌネント、ディレクティブ、パむプなどのボむラヌプレヌトを[`ng generate`](cli/generate)で生成したしょう。 -* 新しいアプリケヌションをデプロむし、[`ng deploy`](cli/deploy)で実際のナヌザヌが利甚できるようにしたしょう。 +- 新しいアプリケヌションをデプロむし、[`ng deploy`](cli/deploy)で実際のナヌザヌが利甚できるようにしたしょう。 -* [`ng e2e`](cli/e2e)でアプリケヌションのE2Eテストをセットアップしお実行したしょう。 +- [`ng e2e`](cli/e2e)でアプリケヌションのE2Eテストをセットアップしお実行したしょう。 From b0b63be1e7804292fa37f0a59fabf6255e4979c4 Mon Sep 17 00:00:00 2001 From: Suguru Inatomi Date: Thu, 20 Nov 2025 15:56:21 +0900 Subject: [PATCH 25/55] fix: migrate contents /tutorials/deferrable-views --- .../1-what-are-deferrable-views/README.en.md | 9 ++++----- .../steps/1-what-are-deferrable-views/README.md | 11 +++++------ .../2-loading-error-placeholder/README.en.md | 6 +++--- .../steps/2-loading-error-placeholder/README.md | 4 ++-- .../steps/3-defer-triggers/README.en.md | 15 +++++++++------ .../steps/3-defer-triggers/README.md | 15 +++++++++------ 6 files changed, 32 insertions(+), 28 deletions(-) diff --git a/adev-ja/src/content/tutorials/deferrable-views/steps/1-what-are-deferrable-views/README.en.md b/adev-ja/src/content/tutorials/deferrable-views/steps/1-what-are-deferrable-views/README.en.md index 89e7690f67..97abbd37b2 100644 --- a/adev-ja/src/content/tutorials/deferrable-views/steps/1-what-are-deferrable-views/README.en.md +++ b/adev-ja/src/content/tutorials/deferrable-views/steps/1-what-are-deferrable-views/README.en.md @@ -1,7 +1,7 @@ # What are deferrable views? A fully rendered Angular page may contain many different components, directives, and pipes. While certain parts of the page should be shown to the user immediately, there may be portions that can wait to display until later. -Angular's *deferrable views*, using the `@defer` syntax, can help you speed up your application by telling Angular to wait to download the JavaScript for the parts of the page that don't need to be shown right away. +Angular's _deferrable views_, using the `@defer` syntax, can help you speed up your application by telling Angular to wait to download the JavaScript for the parts of the page that don't need to be shown right away. In this activity, you'll learn how to use deferrable views to defer load a section of your component template. @@ -25,14 +25,13 @@ In your browser's developer console, you can see that the `article-comments-comp Initial chunk files | Names | Raw size chunk-NNSQHFIE.js | - | 769.00 kB | -main.js | main | 229.25 kB | +main.js | main | 229.25 kB | -Lazy chunk files | Names | Raw size -chunk-T5UYXUSI.js | article-comments-component | 1.84 kB | +Lazy chunk files | Names | Raw size +chunk-T5UYXUSI.js | article-comments-component | 1.84 kB |
    - Great work! You’ve learned the basics of deferrable views. diff --git a/adev-ja/src/content/tutorials/deferrable-views/steps/1-what-are-deferrable-views/README.md b/adev-ja/src/content/tutorials/deferrable-views/steps/1-what-are-deferrable-views/README.md index 2896ec3511..10be8ea3a4 100644 --- a/adev-ja/src/content/tutorials/deferrable-views/steps/1-what-are-deferrable-views/README.md +++ b/adev-ja/src/content/tutorials/deferrable-views/steps/1-what-are-deferrable-views/README.md @@ -1,7 +1,7 @@ # 遅延可胜ビュヌずは 完党にレンダリングされたAngularペヌゞには、倚くの異なるコンポヌネント、ディレクティブ、パむプが含たれおいる堎合がありたす。ペヌゞの特定の郚分はナヌザヌにすぐに衚瀺する必芁がありたすが、埌で衚瀺されるたで埅぀こずができる郚分もありたす。 -Angularの*遅延可胜ビュヌ*は`@defer`構文を䜿甚しお、すぐに衚瀺する必芁のないペヌゞの郚分のJavaScriptのダりンロヌドをAngularに埅たせるこずで、アプリケヌションの高速化に圹立ちたす。 +Angularの_遅延可胜ビュヌ_は`@defer`構文を䜿甚しお、すぐに衚瀺する必芁のないペヌゞの郚分のJavaScriptのダりンロヌドをAngularに埅たせるこずで、アプリケヌションの高速化に圹立ちたす。 このアクティビティでは、遅延可胜ビュヌを䜿甚しおコンポヌネントテンプレヌトのセクションのロヌドを遅延させる方法を孊習したす。 @@ -24,15 +24,14 @@ Angularの*遅延可胜ビュヌ*は`@defer`構文を䜿甚しお、すぐに衚 Initial chunk files | Names | Raw size -chunk-NNSQHFIE.js | - | 769.00 kB | -main.js | main | 229.25 kB | +chunk-NNSQHFIE.js | - | 769.00 kB | +main.js | main | 229.25 kB | -Lazy chunk files | Names | Raw size -chunk-T5UYXUSI.js | article-comments-component | 1.84 kB | +Lazy chunk files | Names | Raw size +chunk-T5UYXUSI.js | article-comments-component | 1.84 kB |
    - よくできたしたあなたは遅延可胜ビュヌの基本を孊びたした。 diff --git a/adev-ja/src/content/tutorials/deferrable-views/steps/2-loading-error-placeholder/README.en.md b/adev-ja/src/content/tutorials/deferrable-views/steps/2-loading-error-placeholder/README.en.md index 0dd4d85f4d..9d32e42dc2 100644 --- a/adev-ja/src/content/tutorials/deferrable-views/steps/2-loading-error-placeholder/README.en.md +++ b/adev-ja/src/content/tutorials/deferrable-views/steps/2-loading-error-placeholder/README.en.md @@ -65,12 +65,12 @@ Next add a `@loading` block to the component template. The `@loading` block accepts two optional parameters: -* `minimum`: the amount of time that this block should be shown -* `after`: the amount of time to wait after loading begins before showing the loading template +- `minimum`: the amount of time that this block should be shown +- `after`: the amount of time to wait after loading begins before showing the loading template Both parameters are specified in time increments of milliseconds (ms) or seconds (s). -Update `app.ts` to include a `@loading` block with a minimum parameter of `1s` as well as an after parameter with the value 500ms to the @loading block. +Update `app.ts` to include a `@loading` block with a minimum parameter of `1s` as well as an after parameter with the value 500ms to the @loading block. @defer { diff --git a/adev-ja/src/content/tutorials/deferrable-views/steps/2-loading-error-placeholder/README.md b/adev-ja/src/content/tutorials/deferrable-views/steps/2-loading-error-placeholder/README.md index 8f121a09df..db88355f46 100644 --- a/adev-ja/src/content/tutorials/deferrable-views/steps/2-loading-error-placeholder/README.md +++ b/adev-ja/src/content/tutorials/deferrable-views/steps/2-loading-error-placeholder/README.md @@ -65,8 +65,8 @@ `@loading`ブロックは、2぀のオプションパラメヌタヌを受け入れたす。 -* `minimum`このブロックを衚瀺する時間 -* `after`読み蟌み開始埌、読み蟌みテンプレヌトを衚瀺するたでの埅ち時間 +- `minimum`このブロックを衚瀺する時間 +- `after`読み蟌み開始埌、読み蟌みテンプレヌトを衚瀺するたでの埅ち時間 どちらのパラメヌタヌも、ミリ秒(ms)たたは秒(s)の時間単䜍で指定されたす。 diff --git a/adev-ja/src/content/tutorials/deferrable-views/steps/3-defer-triggers/README.en.md b/adev-ja/src/content/tutorials/deferrable-views/steps/3-defer-triggers/README.en.md index a0cfc837a8..4308728f59 100644 --- a/adev-ja/src/content/tutorials/deferrable-views/steps/3-defer-triggers/README.en.md +++ b/adev-ja/src/content/tutorials/deferrable-views/steps/3-defer-triggers/README.en.md @@ -29,8 +29,8 @@ If the `when` condition evaluates to `false`, the `defer` block is not reverted You can define multiple event triggers at once, these triggers will be evaluated as OR conditions. -* Ex: `@defer (on viewport; on timer(2s))` -* Ex: `@defer (on viewport; when customizedCondition)` +- Ex: `@defer (on viewport; on timer(2s))` +- Ex: `@defer (on viewport; when customizedCondition)` In this activity, you'll learn how to use triggers to specify the condition to load the deferrable views. @@ -63,8 +63,9 @@ Next, update the template to include a button with the label "Show all comments" @defer (on hover) { - + } @placeholder (minimum 1s) { +

    Placeholder for comments

    } @loading (minimum 1s; after 500ms) {

    Loading comments...

    @@ -84,8 +85,9 @@ Update the `@defer` block in the template to use the `on interaction` trigger. P @defer (on hover; on interaction(showComments)) { - + } @placeholder (minimum 1s) { +

    Placeholder for comments

    } @loading (minimum 1s; after 500ms) {

    Loading comments...

    @@ -95,8 +97,9 @@ Update the `@defer` block in the template to use the `on interaction` trigger. P
    With these changes, the page will wait for one of the following conditions before rendering the comments section: -* User hovers the comments section’s placeholder -* User clicks on the “Show all comments" button + +- User hovers the comments section’s placeholder +- User clicks on the “Show all comments" button You can reload the page to try out different triggers to render the comments section. diff --git a/adev-ja/src/content/tutorials/deferrable-views/steps/3-defer-triggers/README.md b/adev-ja/src/content/tutorials/deferrable-views/steps/3-defer-triggers/README.md index 5d72f124c8..c54a841d99 100644 --- a/adev-ja/src/content/tutorials/deferrable-views/steps/3-defer-triggers/README.md +++ b/adev-ja/src/content/tutorials/deferrable-views/steps/3-defer-triggers/README.md @@ -29,8 +29,8 @@ 耇数のむベントトリガヌを䞀床に定矩できたす。これらのトリガヌはOR条件ずしお評䟡されたす。 -* 䟋: `@defer (on viewport; on timer(2s))` -* 䟋: `@defer (on viewport; when customizedCondition)` +- 䟋: `@defer (on viewport; on timer(2s))` +- 䟋: `@defer (on viewport; when customizedCondition)` このアクティビティでは、トリガヌを䜿甚しお遅延可胜ビュヌをロヌドする条件を指定する方法を孊習したす。 @@ -63,8 +63,9 @@ @defer (on hover) { - + } @placeholder (minimum 1s) { +

    Placeholder for comments

    } @loading (minimum 1s; after 500ms) {

    Loading comments...

    @@ -84,8 +85,9 @@ NOTE: [テンプレヌト倉数に関する詳现に぀いおは、ドキュメ @defer (on hover; on interaction(showComments)) { - + } @placeholder (minimum 1s) { +

    Placeholder for comments

    } @loading (minimum 1s; after 500ms) {

    Loading comments...

    @@ -95,8 +97,9 @@ NOTE: [テンプレヌト倉数に関する詳现に぀いおは、ドキュメ
    これらの倉曎により、ペヌゞは次の条件のいずれかが満たされるたで、コメントセクションのレンダリングを埅機したす。 -* ナヌザヌがコメントセクションのプレヌスホルダヌにホバヌする -* ナヌザヌが「すべおのコメントを衚瀺」ボタンをクリックする + +- ナヌザヌがコメントセクションのプレヌスホルダヌにホバヌする +- ナヌザヌが「すべおのコメントを衚瀺」ボタンをクリックする ペヌゞをリロヌドしお、コメントセクションをレンダリングするためのさたざたなトリガヌを詊すこずができたす。 From 4fc4d50b9a164616534b9c91f1737da7c5ad86bd Mon Sep 17 00:00:00 2001 From: Suguru Inatomi Date: Thu, 20 Nov 2025 15:56:54 +0900 Subject: [PATCH 26/55] fix: migrate contents /tutorials/home --- adev-ja/src/content/tutorials/home.en.md | 3 +++ adev-ja/src/content/tutorials/home.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/adev-ja/src/content/tutorials/home.en.md b/adev-ja/src/content/tutorials/home.en.md index b6b745858d..2cdea3d03b 100644 --- a/adev-ja/src/content/tutorials/home.en.md +++ b/adev-ja/src/content/tutorials/home.en.md @@ -6,6 +6,9 @@ Welcome to the Angular tutorials! These tutorials will guide you through the cor via the Playground + + via MCP Server + via npm diff --git a/adev-ja/src/content/tutorials/home.md b/adev-ja/src/content/tutorials/home.md index bc2d6627f9..bb86cd6b91 100644 --- a/adev-ja/src/content/tutorials/home.md +++ b/adev-ja/src/content/tutorials/home.md @@ -6,6 +6,9 @@ Angularチュヌトリアルぞようこそこれらのチュヌトリアル Playground を䜿甚 + + MCP Server を䜿甚 + npm を䜿甚 From 202817253d61ba1eb47edba4f0e851ecd966103a Mon Sep 17 00:00:00 2001 From: Suguru Inatomi Date: Thu, 20 Nov 2025 16:44:58 +0900 Subject: [PATCH 27/55] fix: migrate contents /tutorials --- .../tutorials/learn-angular/intro/README.en.md | 2 +- .../steps/11-optimizing-images/README.en.md | 5 ++--- .../steps/11-optimizing-images/README.md | 5 ++--- .../steps/12-enable-routing/README.en.md | 9 ++++----- .../learn-angular/steps/12-enable-routing/README.md | 11 ++++------- .../steps/13-define-a-route/README.en.md | 10 +++++----- .../learn-angular/steps/13-define-a-route/README.md | 12 +++++------- .../learn-angular/steps/15-forms/README.en.md | 4 ++-- .../tutorials/learn-angular/steps/15-forms/README.md | 4 ++-- .../steps/16-form-control-values/README.en.md | 6 +++--- .../steps/16-form-control-values/README.md | 6 +++--- .../learn-angular/steps/22-pipes/README.en.md | 8 ++++---- .../tutorials/learn-angular/steps/22-pipes/README.md | 8 ++++---- .../steps/24-create-a-pipe/README.en.md | 3 ++- .../learn-angular/steps/8-input/README.en.md | 4 ++-- .../learn-angular/steps/9-output/README.en.md | 10 +++++----- .../tutorials/learn-angular/steps/9-output/README.md | 9 ++++----- .../README.en.md | 3 ++- .../README.md | 3 ++- .../README.en.md | 6 +++--- .../2-deriving-state-with-computed-signals/README.md | 6 +++--- .../README.en.md | 2 +- .../3-deriving-state-with-linked-signals/README.md | 2 +- .../4-managing-async-data-with-signals/README.en.md | 2 +- .../4-managing-async-data-with-signals/README.md | 2 +- .../README.en.md | 4 ++-- .../5-component-communication-with-signals/README.md | 4 ++-- .../README.en.md | 2 +- .../6-two-way-binding-with-model-signals/README.md | 2 +- .../steps/7-using-signals-with-services/README.en.md | 2 +- .../steps/7-using-signals-with-services/README.md | 2 +- .../8-using-signals-with-directives/README.en.md | 2 +- .../steps/8-using-signals-with-directives/README.md | 2 +- 33 files changed, 78 insertions(+), 84 deletions(-) diff --git a/adev-ja/src/content/tutorials/learn-angular/intro/README.en.md b/adev-ja/src/content/tutorials/learn-angular/intro/README.en.md index 316e3b04b5..92210d5306 100644 --- a/adev-ja/src/content/tutorials/learn-angular/intro/README.en.md +++ b/adev-ja/src/content/tutorials/learn-angular/intro/README.en.md @@ -14,4 +14,4 @@ Alright, let's [get started](/tutorials/learn-angular/1-components-in-angular). ## Using AI for Development -In case you're following this tutorial in your preferred AI powered IDE, [check out Angular prompt rules and best practices](/ai/develop-with-ai). \ No newline at end of file +In case you're following this tutorial in your preferred AI powered IDE, [check out Angular prompt rules and best practices](/ai/develop-with-ai). diff --git a/adev-ja/src/content/tutorials/learn-angular/steps/11-optimizing-images/README.en.md b/adev-ja/src/content/tutorials/learn-angular/steps/11-optimizing-images/README.en.md index f40d54d5e2..6c085fe927 100644 --- a/adev-ja/src/content/tutorials/learn-angular/steps/11-optimizing-images/README.en.md +++ b/adev-ja/src/content/tutorials/learn-angular/steps/11-optimizing-images/README.en.md @@ -35,8 +35,7 @@ To enable the `NgOptimizedImage` directive, swap out the `src` attribute for `ng import { NgOptimizedImage } from '@angular/common'; @Component({ - template: ` - ... +template: ` ...
  • Static Image: Angular logo @@ -47,7 +46,7 @@ import { NgOptimizedImage } from '@angular/common';
  • ... `, - imports: [NgOptimizedImage], +imports: [NgOptimizedImage], })
    diff --git a/adev-ja/src/content/tutorials/learn-angular/steps/11-optimizing-images/README.md b/adev-ja/src/content/tutorials/learn-angular/steps/11-optimizing-images/README.md index 3fcc93abe9..467d324e7f 100644 --- a/adev-ja/src/content/tutorials/learn-angular/steps/11-optimizing-images/README.md +++ b/adev-ja/src/content/tutorials/learn-angular/steps/11-optimizing-images/README.md @@ -35,8 +35,7 @@ import { NgOptimizedImage } from '@angular/common'; import { NgOptimizedImage } from '@angular/common'; @Component({ - template: ` - ... +template: ` ...
  • 静的画像: Angular ロゎ @@ -47,7 +46,7 @@ import { NgOptimizedImage } from '@angular/common';
  • ... `, - imports: [NgOptimizedImage], +imports: [NgOptimizedImage], })
    diff --git a/adev-ja/src/content/tutorials/learn-angular/steps/12-enable-routing/README.en.md b/adev-ja/src/content/tutorials/learn-angular/steps/12-enable-routing/README.en.md index fd0fbfef48..3009baa314 100644 --- a/adev-ja/src/content/tutorials/learn-angular/steps/12-enable-routing/README.en.md +++ b/adev-ja/src/content/tutorials/learn-angular/steps/12-enable-routing/README.en.md @@ -39,7 +39,7 @@ import {provideRouter} from '@angular/router'; import {routes} from './app.routes'; export const appConfig: ApplicationConfig = { - providers: [provideRouter(routes)], +providers: [provideRouter(routes)], };
    @@ -55,16 +55,15 @@ Update the template for `App` by adding `` import {RouterOutlet} from '@angular/router'; @Component({ - ... - template: ` -