@dsivd/prestations-ng 19.2.0-beta.3 → 19.2.0-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/AI_GUIDELINES.md +152 -0
  2. package/ANGULAR_SIGNALS.md +6 -2
  3. package/CHANGELOG.md +476 -0
  4. package/CONTRIBUTING.md +128 -8
  5. package/ESLINT_PLUGIN.md +262 -30
  6. package/GOOD_PRACTICES.md +983 -388
  7. package/INTRODUCTION_ANGULAR_SIGNALS.md +227 -155
  8. package/README.md +22 -12
  9. package/UPGRADING_V18.md +5 -5
  10. package/UPGRADING_V19.md +636 -19
  11. package/eslint/configs/spec-ts-recommended.mjs +34 -0
  12. package/eslint/configs/template-recommended.mjs +2 -0
  13. package/eslint/configs/template-rules.mjs +14 -2
  14. package/eslint/configs/ts-recommended.mjs +11 -0
  15. package/eslint/configs/ts-rules.mjs +6 -2
  16. package/eslint/form-reads.mjs +63 -0
  17. package/eslint/index.mjs +17 -0
  18. package/eslint/rules/index.mjs +6 -0
  19. package/eslint/rules/no-direct-signal-mutation.mjs +162 -41
  20. package/eslint/rules/no-item-track-in-form-list.mjs +173 -0
  21. package/eslint/rules/no-uninvoked-signal-in-template.mjs +8 -3
  22. package/eslint/rules/require-model-change.mjs +89 -0
  23. package/eslint/rules/require-track-index.mjs +162 -0
  24. package/eslint/signal-names.mjs +127 -21
  25. package/eslint/template-ast.mjs +12 -2
  26. package/fesm2022/dsivd-prestations-ng.mjs +2889 -2061
  27. package/fesm2022/dsivd-prestations-ng.mjs.map +1 -1
  28. package/package.json +1 -2
  29. package/schematics/migration-collection.json +5 -0
  30. package/schematics/ng-add/index.js +2 -4
  31. package/schematics/ng-update/migrations/update-13_2_0/index.js +7 -2
  32. package/schematics/ng-update/migrations/update-19_2_0/index.js +52 -0
  33. package/schematics/utility/add-allowed-common-js-dependencies.js +39 -29
  34. package/schematics/utility/form-signal/class-migration.js +795 -0
  35. package/schematics/utility/form-signal/edits.js +34 -0
  36. package/schematics/utility/form-signal/form-members.js +318 -0
  37. package/schematics/utility/form-signal/form-signal-migration.js +134 -0
  38. package/schematics/utility/form-signal/page-classes.js +139 -0
  39. package/schematics/utility/form-signal/template-migration.js +775 -0
  40. package/schematics/utility/never-connected-migration.js +87 -0
  41. package/schematics/utility/remove-emit-decorator-metadata.js +8 -9
  42. package/schematics/utility/typescript-files.js +95 -0
  43. package/src/eslint/configs/__tests__/configs.test.mjs +61 -2
  44. package/src/eslint/configs/spec-ts-recommended.mjs +34 -0
  45. package/src/eslint/configs/template-recommended.mjs +2 -0
  46. package/src/eslint/configs/template-rules.mjs +14 -2
  47. package/src/eslint/configs/ts-recommended.mjs +11 -0
  48. package/src/eslint/configs/ts-rules.mjs +6 -2
  49. package/src/eslint/form-reads.mjs +63 -0
  50. package/src/eslint/index.mjs +17 -0
  51. package/src/eslint/rules/__tests__/no-direct-signal-mutation.test.mjs +200 -0
  52. package/src/eslint/rules/__tests__/no-item-track-in-form-list.test.mjs +234 -0
  53. package/src/eslint/rules/__tests__/no-uninvoked-signal-in-template.test.mjs +6 -0
  54. package/src/eslint/rules/__tests__/require-model-change.test.mjs +93 -0
  55. package/src/eslint/rules/__tests__/require-track-index.test.mjs +106 -0
  56. package/src/eslint/rules/index.mjs +6 -0
  57. package/src/eslint/rules/no-direct-signal-mutation.mjs +162 -41
  58. package/src/eslint/rules/no-item-track-in-form-list.mjs +173 -0
  59. package/src/eslint/rules/no-uninvoked-signal-in-template.mjs +8 -3
  60. package/src/eslint/rules/require-model-change.mjs +89 -0
  61. package/src/eslint/rules/require-track-index.mjs +162 -0
  62. package/src/eslint/signal-names.mjs +127 -21
  63. package/src/eslint/template-ast.mjs +12 -2
  64. package/types/dsivd-prestations-ng.d.ts +719 -243
  65. package/dsivd-prestations-ng-19.2.0-beta.3.tgz +0 -0
package/GOOD_PRACTICES.md CHANGED
@@ -1,97 +1,107 @@
1
- # Utilisation technique (DEV)
1
+ # Technical usage (DEV)
2
2
 
3
- > Ce guide décrit les bonnes pratiques pour développer une prestation avec `prestations-ng`.
4
- > Il a été mis à jour pour la version **v19+** : composants **standalone**, **signals** et
5
- > fonction **`inject`** (plus de modules, plus d'injection par constructeur).
3
+ > This guide describes the good practices to develop a prestation with `prestations-ng`.
4
+ > It has been updated for version **v19+**: **standalone** components, **signals** and the
5
+ > **`inject`** function (no more modules, no more constructor injection). Since **v19.2**,
6
+ > prestations-ng is **zoneless**: the examples hold the state of your components in signals,
7
+ > which works with or without zone.js (see [Zoneless application](good-practices#zoneless_application)).
6
8
  >
7
- > 📚 Pour aller plus loin :
9
+ > 📚 To go further:
8
10
  > [ANGULAR_SIGNALS.md](ANGULAR_SIGNALS.md) · [COMPONENTS.md](COMPONENTS.md) · [UPGRADING_V19.md](UPGRADING_V19.md)
9
11
 
10
- ## Sommaire
12
+ ## Table of contents
11
13
 
12
14
  - [Documentation](good-practices#documentation)
13
- - [Mise à jour de la librairie](good-practices#mise___jour_de_la_librairie)
14
- - [Accessibilité](good-practices#accessibilit_)
15
- - [Structure HTML](good-practices#structure_html)
16
- - [Le focus](good-practices#le_focus)
17
- - [La balise `<label>`](good-practices#la_balise__code__lt_label_gt___code_)
18
- - [La balise `<ul>` ou `<ol>`](good-practices#la_balise__code__lt_ul_gt___code__ou__code__lt_ol_gt___code_)
19
- - [La balise `<fieldset>` et `<legend>`](good-practices#la_balise__code__lt_fieldset_gt___code__et__code__lt_legend_gt___code_)
20
- - [Liseuse d'écran (afficher / masquer)](good-practices#liseuse_d__cran__afficher___masquer_)
21
- - [Une page prestations-ng](good-practices#une_page_prestations-ng)
22
- - [Le routage de vos pages](good-practices#le_routage_de_vos_pages)
23
- - [Formulaire simple](good-practices#formulaire_simple)
24
- - [Formulaire complexe (sous-routes)](good-practices#formulaire_complexe__sous-routes_)
25
- - [Création d'un composant réutilisable](good-practices#cr_ation_d_un_composant_r_utilisable)
26
- - [Exemple avec foehn-input-date de prestations-ng](good-practices#exemple_avec_foehn-input-date_de_prestations-ng)
27
- - [Afficher la validation globale du composant](good-practices#afficher_la_validation_globale_du_composant)
28
- - [Éviter des problèmes d'affichage d'erreurs dans une boucle `@for`](good-practices#_viter_des_probl_mes_d_affichage_d_erreurs_dans_une_boucle__code__for__code_)
29
- - [Validation du formulaire](good-practices#validation_du_formulaire)
30
- - [Gestion standard](good-practices#gestion_standard)
31
- - [Gestion manuelle](good-practices#gestion_manuelle)
15
+ - [Updating the library](good-practices#updating_the_library)
16
+ - [Accessibility](good-practices#accessibility)
17
+ - [HTML structure](good-practices#html_structure)
18
+ - [Focus](good-practices#focus)
19
+ - [The `<label>` tag](good-practices#the__code__lt_label_gt___code__tag)
20
+ - [The `<ul>` or `<ol>` tag](good-practices#the__code__lt_ul_gt___code__or__code__lt_ol_gt___code__tag)
21
+ - [The `<fieldset>` and `<legend>` tags](good-practices#the__code__lt_fieldset_gt___code__and__code__lt_legend_gt___code__tags)
22
+ - [Screen reader (show / hide)](good-practices#screen_reader__show___hide_)
23
+ - [A prestations-ng page](good-practices#a_prestations-ng_page)
24
+ - [Binding the fields of the form](good-practices#binding_the_fields_of_the_form)
25
+ - [Zoneless application](good-practices#zoneless_application)
26
+ - [Displaying an asynchronous state](good-practices#displaying_an_asynchronous_state)
27
+ - [Deriving a state from view queries](good-practices#deriving_a_state_from_view_queries)
28
+ - [Acting on the DOM after rendering](good-practices#acting_on_the_dom_after_rendering)
29
+ - [Testing a zoneless component](good-practices#testing_a_zoneless_component)
30
+ - [HTTP errors and file downloads](good-practices#http_errors_and_file_downloads)
31
+ - [Routing your pages](good-practices#routing_your_pages)
32
+ - [Simple form](good-practices#simple_form)
33
+ - [Complex form (sub-routes)](good-practices#complex_form__sub-routes_)
34
+ - [Creating a reusable component](good-practices#creating_a_reusable_component)
35
+ - [Example with foehn-input-date of prestations-ng](good-practices#example_with_foehn-input-date_of_prestations-ng)
36
+ - [Displaying the global validation of the component](good-practices#displaying_the_global_validation_of_the_component)
37
+ - [Avoiding error display problems in a `@for` loop](good-practices#avoiding_error_display_problems_in_a__code__for__code__loop)
38
+ - [Types of the form fields](good-practices#types_of_the_form_fields)
39
+ - [Form validation](good-practices#form_validation)
40
+ - [Standard handling](good-practices#standard_handling)
41
+ - [Manual handling](good-practices#manual_handling)
32
42
  - [Back-end](good-practices#back-end)
33
43
  - [Front-end](good-practices#front-end)
34
- - [Validation manuelle d'un composant](good-practices#validation_manuelle_d_un_composant)
35
- - [Cacher une erreur](good-practices#cacher_une_erreur)
36
- - [Afficher une erreur](good-practices#afficher_une_erreur)
44
+ - [Manual validation of a component](good-practices#manual_validation_of_a_component)
45
+ - [Hiding an error](good-practices#hiding_an_error)
46
+ - [Displaying an error](good-practices#displaying_an_error)
37
47
 
38
- > ⚠️ Dans toutes vos pages HTML vous devez avoir un `<foehn-form>` et celui-ci **ne peut pas être
39
- > conditionnel** (pas de `@if` autour de `<foehn-form>`).
48
+ > ⚠️ All your HTML pages must have a `<foehn-form>`, and it **can't be
49
+ > conditional** (no `@if` around `<foehn-form>`).
40
50
 
41
51
  ## Documentation
42
52
 
43
53
  - [PrestaKit](https://www.vd.ch/toutes-les-autorites/departements/departement-des-infrastructures-et-des-ressources-humaines-dirh/direction-generale-du-numerique-et-des-systemes-dinformation-dgnsi/prestakit-sdk-pour-le-developpement-des-prestations-en-ligne/)
44
54
  - [prestations-ng](https://dsi-vd.github.io/prestations-ng/)
45
- - [prestations-ng (doc autogénérée)](https://dsi-vd.github.io/prestations-ng/generateddoc/)
46
- - [foehn](https://dsi-vd.github.io/foehn-design-system/components/detail/formulaire-prestation--default.html) (Charte graphique)
55
+ - [prestations-ng (generated doc)](https://dsi-vd.github.io/prestations-ng/generateddoc/)
56
+ - [foehn](https://dsi-vd.github.io/foehn-design-system/components/detail/formulaire-prestation--default.html) (Graphic charter)
47
57
  - [CSS](https://www.w3schools.com/css/default.asp)
48
58
  - [Bootstrap](https://getbootstrap.com/docs/5.3/layout/grid/)
49
59
  - [Flex - Bootstrap](https://getbootstrap.com/docs/5.3/utilities/flex/)
50
60
  - [Flex](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)
51
61
  - [HTML](https://www.w3schools.com/html/default.asp)
52
- - [Éléments de section](https://www.alsacreations.com/article/lire/1376-html5-section-article-nav-header-footer-aside.html)
62
+ - [Section elements](https://www.alsacreations.com/article/lire/1376-html5-section-article-nav-header-footer-aside.html) (in French)
53
63
  - [Description list](https://www.w3schools.com/tags/tag_dl.asp)
54
64
  - [RXJS](https://rxjs-dev.firebaseapp.com/)
55
65
 
56
- ## Mise à jour de la librairie
66
+ ## Updating the library
57
67
 
58
- > ℹ️ Maintenez à jour vos librairies en vous inscrivant sur la page [PrestaKit](https://www.vd.ch/toutes-les-autorites/departements/departement-des-infrastructures-et-des-ressources-humaines-dirh/direction-generale-du-numerique-et-des-systemes-dinformation-dgnsi/prestakit-sdk-pour-le-developpement-des-prestations-en-ligne/)
59
- > et vous serez ainsi notifié des nouvelles releases. Cela vous permettra de profiter des corrections
60
- > de bug, améliorations et nouvelles fonctionnalités.
68
+ > ℹ️ Keep your libraries up to date by subscribing on the [PrestaKit](https://www.vd.ch/toutes-les-autorites/departements/departement-des-infrastructures-et-des-ressources-humaines-dirh/direction-generale-du-numerique-et-des-systemes-dinformation-dgnsi/prestakit-sdk-pour-le-developpement-des-prestations-en-ligne/)
69
+ > page: you will be notified of the new releases. You will then benefit from the bug fixes,
70
+ > improvements and new features.
61
71
  >
62
- > Prenez le temps de lire le [changelog](CHANGELOG.md) de **prestations-ng** à chaque nouvelle release.
72
+ > Take the time to read the [changelog](CHANGELOG.md) of **prestations-ng** at each new release.
63
73
  >
64
- > N'hésitez pas à ouvrir des tickets JIRA (PRESTAKIT-xxx) dans [PrestaKit (anc SDK Cyber)](https://issuetracker.etat-de-vaud.ch/outils/issuetracker/browse/PRESTAKIT)
65
- > pour signaler des bugs ou même à faire des propositions d'améliorations afin de
66
- > [contribuer](CONTRIBUTING.md) au développement de prestations-ng.
74
+ > Don't hesitate to open JIRA tickets (PRESTAKIT-xxx) in [PrestaKit (formerly SDK Cyber)](https://issuetracker.etat-de-vaud.ch/outils/issuetracker/browse/PRESTAKIT)
75
+ > to report bugs, or even to suggest improvements in order to
76
+ > [contribute](CONTRIBUTING.md) to the development of prestations-ng.
67
77
 
68
- Mettre à jour la librairie prestations-ng (npm) :
78
+ Update the prestations-ng library (npm):
69
79
 
70
80
  ```bash
71
81
  ng update @dsivd/prestations-ng
72
82
  ```
73
83
 
74
- ## Accessibilité
84
+ ## Accessibility
75
85
 
76
- > ℹ️ En développant des prestations pour l'État, nous devons faire tout notre possible pour rendre nos
77
- > pages web les plus accessibles possibles au grand public.
86
+ > ℹ️ When developing prestations for the State, we must do everything we can to make our web pages
87
+ > as accessible as possible to the general public.
78
88
  >
79
- > Prestations-ng fait une bonne partie du boulot pour nous mais c'est au développeur de prendre le
80
- > soin de mettre les efforts qu'il faut pour que la prestation reste accessible.
89
+ > Prestations-ng does a good part of the job for us, but it's up to the developer to make the
90
+ > necessary efforts so that the prestation stays accessible.
81
91
 
82
- ### Structure HTML
92
+ ### HTML structure
83
93
 
84
- > ⚠️ Nous recommandons :
94
+ > ⚠️ We recommend to:
85
95
  >
86
- > - une seule balise h1 (`<h1>`)
87
- > - respecter la hiérarchie h1, h2, h3..
88
- > - regrouper vos informations dans des sections (`<section>`) si vous avez plusieurs h2 (`<h2>`)
89
- > - utiliser la classe CSS `col-md-8` de Bootstrap pour définir la largeur de votre formulaire
90
- > - organisez votre texte avec des paragraphes (`<p>`)
91
- > - utiliser les balises `<dl>`, `<dt>` et `<dd>` pour afficher des clés / valeurs (voir [foehn-recap-section](https://dsi-vd.github.io/prestations-ng/recap))
92
- > - utiliser [foehn-abbr](https://dsi-vd.github.io/prestations-ng/misc) pour les abréviations tant que possible et sinon la balise abbr (`<abbr>`)
96
+ > - have a single h1 tag (`<h1>`)
97
+ > - respect the hierarchy h1, h2, h3..
98
+ > - group your information in sections (`<section>`) if you have several h2 (`<h2>`)
99
+ > - use the Bootstrap CSS class `col-md-8` to define the width of your form
100
+ > - organize your text with paragraphs (`<p>`)
101
+ > - use the `<dl>`, `<dt>` and `<dd>` tags to display keys / values (see [foehn-recap-section](https://dsi-vd.github.io/prestations-ng/recap))
102
+ > - use [foehn-abbr](https://dsi-vd.github.io/prestations-ng/misc) for the abbreviations whenever possible, and the abbr tag (`<abbr>`) otherwise
93
103
 
94
- Ce qu'il ne faut **pas** faire :
104
+ What **not** to do:
95
105
 
96
106
  ```html
97
107
  <h1>...</h1>
@@ -101,7 +111,7 @@ Ce qu'il ne faut **pas** faire :
101
111
  ... ... ...
102
112
  ```
103
113
 
104
- Ce qu'il **faut** faire :
114
+ What **to** do:
105
115
 
106
116
  ```html
107
117
  <h1>...</h1>
@@ -116,27 +126,27 @@ Ce qu'il **faut** faire :
116
126
  <section>...</section>
117
127
  ```
118
128
 
119
- Quelques attributs HTML utiles :
129
+ Some useful HTML attributes:
120
130
 
121
- - Pour les images (`<img>`)
122
- - `title="[texte explicite ici]"`
123
- - `alt="[texte explicite ici]"`
124
- - Pour les liens (`<a>`)
125
- - `title="[texte explicite ici]"`
131
+ - For the images (`<img>`)
132
+ - `title="[explicit text here]"`
133
+ - `alt="[explicit text here]"`
134
+ - For the links (`<a>`)
135
+ - `title="[explicit text here]"`
126
136
  - `target="_blank"`
127
- - [Rendre les balises accessibles](https://www.w3.org/TR/wai-aria-1.2/#intro_ria_accessibility)
137
+ - [Make the tags accessible](https://www.w3.org/TR/wai-aria-1.2/#intro_ria_accessibility)
128
138
  - [`aria-*`](https://w3c.github.io/using-aria/#aria-states-and-properties-aria-attributes)
129
139
  - [`role`](https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute)
130
140
 
131
- ### Le focus
141
+ ### Focus
132
142
 
133
- > ⚠️ Il est important que le focus dans une page HTML soit maîtrisé. Si le focus est perdu, alors la
134
- > liseuse d'écran le sera aussi.
143
+ > ⚠️ It's important that the focus in an HTML page is under control. If the focus is lost, the
144
+ > screen reader is lost too.
135
145
  >
136
- > Si, par exemple, on ouvre une modale en cliquant sur un bouton, alors à la fermeture de la modale,
137
- > le focus doit être remis sur le bouton déclencheur.
146
+ > If, for example, a modal is opened by clicking on a button, then when the modal is closed, the
147
+ > focus must be put back on the triggering button.
138
148
 
139
- Exemple :
149
+ Example:
140
150
 
141
151
  ```html
142
152
  <button
@@ -145,120 +155,129 @@ Exemple :
145
155
  (click)="openModal()"
146
156
  #modalTrigger
147
157
  >
148
- <!-- on déclare le déclencheur de la modale -->
158
+ <!-- we declare the trigger of the modal -->
149
159
  Open Modal
150
160
  </button>
151
161
  <foehn-modal
152
162
  modalHeaderText="Modal dialog"
153
163
  modalSize="modal-lg"
154
- [isModalVisible]="isModalVisible"
155
- (isModalVisibleChange)="updateVisibilityStatus($event)"
164
+ [(isModalVisible)]="isModalVisible"
156
165
  [modalTriggerHtmlElement]="modalTrigger"
157
166
  >
158
- <!-- on utilise le déclencheur -->
167
+ <!-- we use the trigger -->
159
168
  <div>Here is the dialog</div>
160
169
  </foehn-modal>
161
170
  ```
162
171
 
163
- ### La balise `<label>`
172
+ ```ts
173
+ // A signal: the modal is also displayed and hidden without zone.js
174
+ readonly isModalVisible = signal(false);
175
+
176
+ openModal(): void {
177
+ this.isModalVisible.set(true);
178
+ }
179
+ ```
164
180
 
165
- > ⚠️ Tous nos composants `foehn-input-*` disposent d'une balise label ([`<label>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/label))
166
- > qui décrit le champ de saisie. Il est important que celle-ci soit remplie avec un contenu explicite.
181
+ ### The `<label>` tag
182
+
183
+ > ⚠️ All our `foehn-input-*` components have a label tag ([`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label))
184
+ > which describes the input field. It's important that it is filled with an explicit content.
167
185
  >
168
- > Si pour une raison quelconque, le métier ne souhaite pas l'afficher, vous devez tout de même la
169
- > renseigner et ajouter un attribut `[isLabelSrOnly]="true"`. Le label ne sera pas affiché mais
170
- > uniquement lu par la liseuse d'écran.
186
+ > If for any reason the business doesn't want to display it, you must still fill it and add an
187
+ > `[isLabelSrOnly]="true"` attribute. The label won't be displayed, only read by the screen
188
+ > reader.
171
189
 
172
- Exemple :
190
+ Example:
173
191
 
174
192
  ```html
175
193
  <foehn-input-number
176
194
  name="..."
177
195
  [(model)]="..."
178
- [label]="'Le texte que la liseuse va lire'"
196
+ [label]="'The text read by the screen reader'"
179
197
  [isLabelSrOnly]="true"
180
198
  [required]="..."
181
199
  [maxlength]="..."
182
200
  />
183
201
  ```
184
202
 
185
- > 💡 `label`, `isLabelSrOnly`, `required`, ... sont désormais des **input signals** côté composant.
186
- > Vous continuez à les alimenter depuis le template parent via un binding `[label]="..."`.
187
- > À l'intérieur du composant, vous les lisez en les invoquant : `label()`, `required()`, ...
203
+ > 💡 `label`, `isLabelSrOnly`, `required`, ... are now **input signals** in the component.
204
+ > You keep feeding them from the parent template with a `[label]="..."` binding.
205
+ > Inside the component, you read them by calling them: `label()`, `required()`, ...
188
206
 
189
- ### La balise `<ul>` ou `<ol>`
207
+ ### The `<ul>` or `<ol>` tag
190
208
 
191
209
  > ⚠️
192
210
  >
193
- > - L'élément [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul) doit être utilisé
194
- > pour regrouper plusieurs éléments qui n'ont pas de relation d'ordre. Si on hésite entre
195
- > [`<ol>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ol) et
196
- > [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul), on se demandera si changer
197
- > l'ordre des éléments de la liste a un impact : si le déplacement d'un élément change la
198
- > signification, cela signifie que l'ordre est important et qu'il faudra utiliser
199
- > [`<ol>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ol), sinon l'ordre n'importe pas
200
- > et [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul) peut être utilisé.
201
- > - Si [`<ol>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ol) ou
202
- > [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul) ne contient qu'un seul élément
203
- > [`<li>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/li) (non dynamique), alors on se
204
- > demandera si l'utilisation d'une liste est nécessaire et si un paragraphe
205
- > ([`<p>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/p)) ne serait pas une meilleure
211
+ > - The [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) element must be used
212
+ > to group several items that have no order relationship. If you hesitate between
213
+ > [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) and
214
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul), ask yourself whether
215
+ > changing the order of the items of the list has an impact: if moving an item changes the
216
+ > meaning, the order is important and
217
+ > [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) must be used, otherwise
218
+ > the order doesn't matter and [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul)
219
+ > can be used.
220
+ > - If [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) or
221
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) only contains a single
222
+ > [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li) element (not dynamic),
223
+ > ask yourself whether a list is necessary and whether a paragraph
224
+ > ([`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p)) wouldn't be a better
206
225
  > option.
207
- > - Ne **JAMAIS** mettre une autre balise que [`<li>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/li)
208
- > entre deux balises [`<ol>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ol) ou
209
- > [`<ul>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/ul).
226
+ > - **NEVER** put a tag other than [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li)
227
+ > between two [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) or
228
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) tags.
210
229
 
211
- Exemple :
230
+ Example:
212
231
 
213
232
  ```html
214
233
  <ul>
215
- <li>un artichaut</li>
234
+ <li>an artichoke</li>
216
235
  <li>
217
- Les trucs pour le gâteau
218
- <!-- On voit que </li> n'est pas là -->
236
+ The things for the cake
237
+ <!-- Note that </li> isn't there -->
219
238
  <ul>
220
- <li>trois œufs</li>
239
+ <li>three eggs</li>
221
240
  <li>
222
- La génoise
223
- <!-- Là on ouvre une autre liste -->
241
+ The sponge cake
242
+ <!-- Here we open another list -->
224
243
  <ul>
225
- <li>100g de sucre</li>
226
- <li>un œuf</li>
227
- <li>150g de farine</li>
244
+ <li>100g of sugar</li>
245
+ <li>an egg</li>
246
+ <li>150g of flour</li>
228
247
  </ul>
229
248
  </li>
230
- <!-- On ferme la liste la plus imbriquée -->
231
- <li>200g de chocolat</li>
249
+ <!-- We close the most nested list -->
250
+ <li>200g of chocolate</li>
232
251
  </ul>
233
- <!-- On ferme la liste imbriquée avec </li> -->
252
+ <!-- We close the nested list with </li> -->
234
253
  </li>
235
- <li>De l'essuie-tout</li>
254
+ <li>Paper towels</li>
236
255
  <li>
237
- A faire dans l'ordre pour une belle vaisselle
256
+ To do in this order for a nice dishwashing
238
257
  <ol>
239
- <li>Remplir le lave vaisselle</li>
240
- <li>Mettre une pastille pour lave vaisselle</li>
241
- <li>Fermer la porte du lave vaisselle</li>
242
- <li>Lancer le lave vaisselle</li>
258
+ <li>Fill the dishwasher</li>
259
+ <li>Put a dishwasher tablet</li>
260
+ <li>Close the door of the dishwasher</li>
261
+ <li>Start the dishwasher</li>
243
262
  </ol>
244
263
  </li>
245
264
  </ul>
246
265
  ```
247
266
 
248
- ### La balise `<fieldset>` et `<legend>`
267
+ ### The `<fieldset>` and `<legend>` tags
249
268
 
250
- > ⚠️ L'élément HTML [`<fieldset>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/fieldset) est
251
- > utilisé afin de regrouper plusieurs contrôles interactifs ainsi que des étiquettes
252
- > ([`<label>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/label)) dans un formulaire HTML
253
- > et on doit lui associer une légende
254
- > ([`<legend>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/legend)) décrivant ce groupe.
269
+ > ⚠️ The HTML element [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) is
270
+ > used to group several interactive controls as well as labels
271
+ > ([`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label)) in an HTML form,
272
+ > and it must have a caption
273
+ > ([`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend)) describing this group.
255
274
  >
256
- > L'élément HTML [`<legend>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/legend) représente
257
- > une légende pour le contenu de son élément parent
258
- > [`<fieldset>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/fieldset). Il ne peut pas être
259
- > utilisé tout seul.
275
+ > The HTML element [`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend) represents
276
+ > a caption for the content of its parent element
277
+ > [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset). It can't be
278
+ > used on its own.
260
279
 
261
- Exemple :
280
+ Example:
262
281
 
263
282
  ```html
264
283
  <form>
@@ -277,45 +296,46 @@ Exemple :
277
296
  </form>
278
297
  ```
279
298
 
280
- ### Liseuse d'écran (afficher / masquer)
299
+ ### Screen reader (show / hide)
281
300
 
282
- > ⚠️ Il est important de garder en tête qu'une liseuse d'écran va parcourir notre code HTML. De ce
283
- > fait, nous pouvons à tout moment décider de lui afficher explicitement du contenu à lire ou de lui
284
- > masquer du contenu pour ne pas surcharger l'information.
301
+ > ⚠️ It's important to keep in mind that a screen reader goes through our HTML code. So we can
302
+ > decide at any time to explicitly show it content to read, or to hide content from it so as not to
303
+ > overload the information.
285
304
 
286
- - Afficher uniquement pour la liseuse : utiliser la classe CSS `sr-only`
287
- - Masquer du contenu à la liseuse : utiliser l'attribut `aria-hidden="true"`
305
+ - Show only to the screen reader: use the CSS class `sr-only`
306
+ - Hide content from the screen reader: use the attribute `aria-hidden="true"`
288
307
 
289
- Exemple :
308
+ Example:
290
309
 
291
310
  ```html
292
311
  <a href="https://www.vd.ch">
293
312
  <span class="sr-only">
294
- <!-- Afficher uniquement pour la liseuse d'écran -->
295
- Retour à la page d'accueil
313
+ <!-- Show only to the screen reader -->
314
+ Back to the home page
296
315
  </span>
297
316
  <img
298
317
  aria-hidden="true"
299
318
  class="img-fluid footer-logo"
300
- src="[url_vers_mon_image]"
319
+ src="[url_to_my_image]"
301
320
  alt="Canton de Vaud"
302
321
  />
303
- <!-- Masquer uniquement pour la liseuse d'écran -->
322
+ <!-- Hide only from the screen reader -->
304
323
  </a>
305
324
  ```
306
325
 
307
- Le résultat de l'exemple ci-dessus sera un lien représenté par une image pour les voyants et un lien
308
- avec du texte pour les non-voyants.
326
+ The result of the example above is a link represented by an image for sighted people, and a link
327
+ with text for visually impaired people.
309
328
 
310
- ### Une page prestations-ng
329
+ ### A prestations-ng page
311
330
 
312
- 1. Étendre la classe abstraite `AbstractPageComponent` en spécifiant un modèle
313
- 2. Ajouter un titre h1 en utilisant `setPageTitle`
314
- 3. Implémenter la fonction `newForm`
315
- 4. Ajouter le `<foehn-form>` dans la page (⚠️ **il ne doit pas être conditionnel**)
316
- 5. La première balise d'en-tête de votre page doit être un h2 (`<h2>`)
317
- 6. Ajouter `<foehn-navigation>`
318
- 7. Si vous disposez de plusieurs pages, utiliser le composant `<foehn-page-counter>`
331
+ 1. Extend the abstract class `AbstractPageComponent`, specifying a model
332
+ 2. Add an h1 title with `setPageTitle`
333
+ 3. Implement the `newForm` function
334
+ 4. Add the `<foehn-form>` in the page (⚠️ **it must not be conditional**)
335
+ 5. The first heading tag of your page must be an h2 (`<h2>`)
336
+ 6. Add `<foehn-navigation>`
337
+ 7. If you have several pages, use the `<foehn-page-counter>` component
338
+ 8. Bind the fields of the form with `[model]` and `(modelChange)="patchForm([...], $event)"` (see below)
319
339
 
320
340
  `page-one.component.ts`
321
341
 
@@ -323,12 +343,12 @@ avec du texte pour les non-voyants.
323
343
  @Component({
324
344
  templateUrl: './page-one.component.html',
325
345
  imports: [
326
- // chaque composant importe ce dont il a besoin dans son template
346
+ // each component imports what its template needs
327
347
  FoehnFormComponent,
328
348
  FoehnNavigationComponent,
329
349
  FoehnPageCounterComponent,
330
350
  SdkDictionaryPipe,
331
- // ... vos composants foehn-* utilisés dans le template
351
+ // ... your foehn-* components used in the template
332
352
  ],
333
353
  })
334
354
  export class PageOneComponent
@@ -337,7 +357,7 @@ export class PageOneComponent
337
357
  {
338
358
  ngOnInit(): void {
339
359
  super.ngOnInit();
340
- // point (2) : ajoutera le titre h1
360
+ // point (2): adds the h1 title
341
361
  this.setPageTitle(this._dictionaryService.getKeySync('page.one.title'));
342
362
  }
343
363
 
@@ -348,28 +368,36 @@ export class PageOneComponent
348
368
  }
349
369
  ```
350
370
 
351
- > 💡 Plus de `constructor` : les dépendances de `AbstractPageComponent` (dont `_dictionaryService`)
352
- > sont injectées via `inject()` dans la classe abstraite. `activatedRoute` n'est donc plus un
353
- > paramètre de constructeur à passer.
371
+ > 💡 No more `constructor`: the dependencies of `AbstractPageComponent` (including `_dictionaryService`)
372
+ > are injected with `inject()` in the abstract class. `activatedRoute` is therefore no longer a
373
+ > constructor parameter to pass.
354
374
 
355
375
  `page-one.component.html`
356
376
 
357
377
  ```html
358
378
  <div class="container mt-5">
359
379
  <foehn-page-counter />
360
- <!-- point (7) : si besoin -->
380
+ <!-- point (7): if needed -->
361
381
 
362
- <!-- point (4) : doit toujours être présent dans la page et pas conditionnel (pas de @if) -->
382
+ <!-- point (4): must always be present in the page and not conditional (no @if) -->
363
383
  <foehn-form>
364
384
  <div class="row">
365
385
  <div class="col-md-8">
366
- <!-- point (5) : toujours avoir un <h2> en premier dans votre page -->
386
+ <!-- point (5): always have an <h2> first in your page -->
367
387
  <h2>
368
- {{ 'La_clé_du_dictionnaire_de_votre_titre_H2_ici' |
388
+ {{ 'The_dictionary_key_of_your_H2_title_here' |
369
389
  fromDictionary }}
370
390
  </h2>
371
391
 
372
- <!-- [VOS COMPOSANTS FOEHN ICI] -->
392
+ <!-- point (8) -->
393
+ @if (form(); as form) {
394
+ <foehn-input-text
395
+ name="firstName"
396
+ [model]="form.firstName"
397
+ (modelChange)="patchForm(['firstName'], $event)"
398
+ />
399
+ <!-- [YOUR FOEHN COMPONENTS HERE] -->
400
+ }
373
401
 
374
402
  <foehn-navigation
375
403
  id="navigation"
@@ -383,9 +411,258 @@ export class PageOneComponent
383
411
  </div>
384
412
  ```
385
413
 
386
- ## Le routage de vos pages
414
+ ### Binding the fields of the form
415
+
416
+ The `form` of a page is a signal: read it with `form()`, and never modify its value in place. Write a field with
417
+ `patchForm(path, value)`, which copies the objects along the path: the templates, the `computed()` and the
418
+ `effect()` reading the form follow every input of the user.
419
+
420
+ ```html
421
+ @if (form(); as form) {
422
+ <foehn-input-text
423
+ name="address.street"
424
+ [model]="form.address.street"
425
+ (modelChange)="patchForm(['address', 'street'], $event)"
426
+ />
427
+ @for (child of form.children; track $index) {
428
+ <foehn-input-text
429
+ [name]="'children[' + $index + '].firstName'"
430
+ [model]="child.firstName"
431
+ (modelChange)="patchForm(['children', $index, 'firstName'], $event)"
432
+ />
433
+ } }
434
+ ```
435
+
436
+ ```ts
437
+ readonly childrenCount = computed(() => this.form()?.children.length ?? 0);
438
+
439
+ addChild(): void {
440
+ this.patchForm(['children'], [...(this.form()?.children ?? []), new Child()]);
441
+ }
442
+ ```
443
+
444
+ - The path is checked by TypeScript (a typo gives an error listing the valid keys).
445
+ - Never a `[model]` alone on a field the user can change: what the user enters would never reach the form
446
+ (`require-model-change` reports it). A field always disabled (`[disabled]="true"`), only displayed, is bound with
447
+ `[model]` alone.
448
+ - Track the rows of the list by `$index`, as their names (`require-track-index` reports the others): tracked by an
449
+ identifier, a row whose item moves (an item removed before it, the list sorted) would keep the names of its former
450
+ position, and get the values and the errors of another row. Never by the item: `patchForm()` replaces it, the row
451
+ would be created again and lose the focus (`no-item-track-in-form-list` reports it).
452
+ - A detail page (`AbstractListDetailPageComponent`) gives the path of its list with `getListPath()`, and writes the
453
+ item edited with `patchItem()`, `updateItem()` or `setItem()`.
454
+
455
+ ## Zoneless application
456
+
457
+ > ℹ️ Since v19.2, prestations-ng no longer needs zone.js and we recommend that you make your
458
+ > application zoneless (`provideZonelessChangeDetection()`, see
459
+ > [UPGRADING_V19.md](UPGRADING_V19.md#zoneless-optional-but-recommended)).
460
+ >
461
+ > Without zone.js, Angular only refreshes a component when it is notified of a change:
462
+ >
463
+ > - a listener of its template has been called (`(click)`, `(modelChange)`, `(userInput)`, ...),
464
+ > including the `[(model)]` two-way bindings
465
+ > - a signal read by its template has changed (`signal()`, `computed()`, `input()`, `model()`,
466
+ > `toSignal()`, ...)
467
+ > - `ChangeDetectorRef.markForCheck()` has been called, which is what the `async` pipe does when an
468
+ > observable emits
469
+
470
+ ### Displaying an asynchronous state
471
+
472
+ > ⚠️ A field modified elsewhere (in a `subscribe()`, a `setTimeout()`, a `Promise`, a
473
+ > callback, an `effect()`, ...) is no longer displayed until something else refreshes the component.
474
+ > Hold it in a **signal**.
475
+
476
+ What **not** to do:
477
+
478
+ ```ts
479
+ isLoading = true;
480
+
481
+ ngOnInit(): void {
482
+ this.myService.load().subscribe(() => {
483
+ this.isLoading = false; // not displayed without zone.js
484
+ });
485
+ }
486
+ ```
487
+
488
+ What **to** do:
489
+
490
+ ```ts
491
+ readonly isLoading = signal(true);
492
+
493
+ ngOnInit(): void {
494
+ this.myService.load().subscribe(() => {
495
+ this.isLoading.set(false);
496
+ });
497
+ }
498
+ ```
499
+
500
+ ```html
501
+ @if (isLoading()) {
502
+ <p>{{ 'page.loading' | fromDictionary }}</p>
503
+ }
504
+ ```
505
+
506
+ > 💡 For an observable displayed as is, `toSignal(this.myService.load())` or the `async` pipe do
507
+ > the job for you. For data read by a GET, `httpResource()` (or `rxResource()` over the service) also
508
+ > gives `isLoading()`, `hasValue()` and `error()` without a flag written by hand: see "`rxResource()`"
509
+ > in [INTRODUCTION_ANGULAR_SIGNALS.md](INTRODUCTION_ANGULAR_SIGNALS.md).
510
+
511
+ Do the same for a field read by the template that only a method called by a listener of the template
512
+ modifies: the listener notifies Angular, but the same method can later be called from a `subscribe()`
513
+ or an `effect()`, and the field would no longer be displayed. A signal notifies Angular whoever
514
+ modifies it.
515
+
516
+ In your pages (`AbstractPageComponent`), `form` and `reference` are signals too: write the form with `patchForm()`,
517
+ never in place, whoever calls the method (a listener, a callback, an `effect()`, ...). No `markForCheck()` is needed:
518
+
519
+ ```ts
520
+ ngOnInit(): void {
521
+ super.ngOnInit();
522
+ this.sessionInfoWithApplicationService.prefillForm((info) => {
523
+ this.patchForm(['firstName'], info?.firstName ?? null);
524
+ this.patchForm(['lastName'], info?.lastName ?? null);
525
+ });
526
+ }
527
+ ```
528
+
529
+ See "Binding the fields of the form" above.
530
+
531
+ ### Deriving a state from view queries
532
+
533
+ > ⚠️ A field read by the template and modified in `ngAfterViewInit()`, `ngAfterContentInit()` or
534
+ > `ngAfterViewChecked()` is no longer displayed until something else refreshes the component (with
535
+ > zone.js, the next refresh displayed it, after an `NG0100` error in development).
536
+ > Compute it with `computed()` from `viewChild()` or `contentChild()`.
537
+
538
+ What **not** to do:
539
+
540
+ ```ts
541
+ @ViewChild('referenceLink') referenceLink?: TemplateRef<unknown>;
542
+ columns: FoehnTableColumnConfiguration<Order>[] = [];
543
+
544
+ ngAfterViewInit(): void {
545
+ // not displayed without zone.js
546
+ this.columns = [{ id: 'reference', columnLabelKey: 'orders.reference', template: this.referenceLink }];
547
+ }
548
+ ```
549
+
550
+ What **to** do:
551
+
552
+ ```ts
553
+ readonly referenceLink = viewChild<TemplateRef<unknown>>('referenceLink');
554
+ readonly columns = computed<FoehnTableColumnConfiguration<Order>[]>(() => [
555
+ { id: 'reference', columnLabelKey: 'orders.reference', template: this.referenceLink() },
556
+ ]);
557
+ ```
558
+
559
+ ```html
560
+ <foehn-table
561
+ [name]="'orders'"
562
+ [columnsConfiguration]="columns()"
563
+ [model]="orders()"
564
+ ></foehn-table>
565
+
566
+ <ng-template #referenceLink let-order="item">
567
+ <a [routerLink]="['/demande', order.id]">{{ order.reference }}</a>
568
+ </ng-template>
569
+ ```
570
+
571
+ > 💡 The `computed()` follows the result of the `viewChild()`, including when the element appears or
572
+ > disappears in an `@if`: no need to hide the content until it is resolved. If the element must
573
+ > always exist, `viewChild.required()` guarantees it (error `NG0951` otherwise).
574
+
575
+ ### Acting on the DOM after rendering
576
+
577
+ > ⚠️ `NgZone` (`onStable`, `onMicrotaskEmpty`, `run()`, ...) no longer works without zone.js, and a
578
+ > `setTimeout()` doesn't wait for the rendering. To act on the rendered DOM (focus, scroll, ...), use
579
+ > `afterNextRender()`.
580
+
581
+ ```ts
582
+ readonly detailsVisible = signal(false);
583
+ readonly detailsField = viewChild<ElementRef<HTMLElement>>('detailsField');
584
+
585
+ private readonly injector = inject(Injector);
586
+
587
+ showDetails(): void {
588
+ this.detailsVisible.set(true);
589
+ // The field only exists once the details are rendered
590
+ afterNextRender(() => this.detailsField()?.nativeElement.focus(), {
591
+ injector: this.injector,
592
+ });
593
+ }
594
+ ```
595
+
596
+ ### Testing a zoneless component
597
+
598
+ > ⚠️ `fixture.detectChanges()` **forces** the refresh: a component that forgets to notify
599
+ > Angular (a field instead of a signal, a missing `markForCheck()`, ...) passes the test, but isn't
600
+ > refreshed in the application. Let Angular refresh the component, as in production, with
601
+ > `await fixture.whenStable()`.
602
+
603
+ ```ts
604
+ it('should display the details', async () => {
605
+ fixture.componentRef.setInput('showDetails', true);
606
+ await fixture.whenStable();
607
+
608
+ expect(fixture.nativeElement.querySelector('.details')).not.toBeNull();
609
+ });
610
+ ```
611
+
612
+ `await fixture.whenStable()` also waits for the pending tasks of the application, such as the debounced
613
+ `userInput` of the prestations-ng inputs: the test doesn't end before them (otherwise
614
+ `NG0205: Injector has already been destroyed`). But it doesn't wait for the HTTP requests of a spec:
615
+ `provideHttpClientTesting()` keeps them pending until the test answers them. Answer them first with
616
+ `HttpTestingController`, then `await fixture.whenStable()`:
617
+
618
+ ```ts
619
+ it('should display the reference of the demand', async () => {
620
+ httpMock.expectOne('api/demande/1').flush({ reference: 'DEM-1' });
621
+ await fixture.whenStable();
622
+
623
+ expect(fixture.nativeElement.textContent).toContain('DEM-1');
624
+ });
625
+ ```
626
+
627
+ Keep `fixture.detectChanges()` for:
628
+
629
+ - checking an intermediate state, before the end of an asynchronous processing
630
+ - the tests with `vi.useFakeTimers()`: the refresh of Angular goes through timers, which must be
631
+ advanced (`await vi.advanceTimersByTimeAsync(...)`), otherwise `whenStable()` never ends
632
+
633
+ > 💡 So that the test goes through the same path as the user, trigger the events in the
634
+ > DOM (`input.dispatchEvent(new Event('change'))`, `button.click()`, ...) rather than calling the
635
+ > methods of the component or of its services.
636
+
637
+ ## HTTP errors and file downloads
638
+
639
+ Import `AbstractHttpService` and `downloadFile` from `@dsivd/prestations-ng`.
640
+
641
+ - In a service extending `AbstractHttpService`, use the RxJS `catchError` operator
642
+ and pass a translated fallback message from your dictionary:
643
+
644
+ ```typescript
645
+ catchError(
646
+ this.catchError(
647
+ this._dictionaryService.getKeySync('your-request.error'),
648
+ ),
649
+ );
650
+ ```
387
651
 
388
- ### Formulaire simple
652
+ The handler reads a non-blank string `message` from the HTTP error body, which
653
+ can be an object or JSON text. Otherwise it uses the supplied fallback, which
654
+ defaults to `'error'`. It shows a danger growl for 10 seconds and propagates a
655
+ new `Error` with the same message to the caller.
656
+
657
+ - In the browser, call `downloadFile(data, 'report.pdf', 'application/pdf')` to
658
+ download a `BlobPart`, such as a string, a `Blob` or an `ArrayBuffer`. Pass
659
+ the desired file name and media type. The media type defaults to
660
+ `application/octet-stream`. The helper creates a temporary object URL and
661
+ releases it after triggering the download.
662
+
663
+ ## Routing your pages
664
+
665
+ ### Simple form
389
666
 
390
667
  `app.routes.ts`
391
668
 
@@ -425,14 +702,14 @@ export const routes: Routes = [
425
702
  ];
426
703
  ```
427
704
 
428
- ### Formulaire complexe (sous-routes)
705
+ ### Complex form (sub-routes)
429
706
 
430
- > ℹ️ Préférez l'utilisation de **sous-routes** (`*.routes.ts`) pour regrouper vos routes et ainsi
431
- > mieux structurer votre projet.
707
+ > ℹ️ Prefer **sub-routes** (`*.routes.ts`) to group your routes and thus better structure your
708
+ > project.
432
709
  >
433
- > Comme il n'y a plus de modules (composants **standalone**), on ne charge plus un `*.module.ts` mais
434
- > un fichier de routes qui exporte une constante `Routes`. Voir [UPGRADING_V19.md](UPGRADING_V19.md)
435
- > pour le détail de la migration.
710
+ > As there are no more modules (**standalone** components), you no longer load a `*.module.ts` but
711
+ > a routes file exporting a `Routes` constant. See [UPGRADING_V19.md](UPGRADING_V19.md)
712
+ > for the details of the migration.
436
713
 
437
714
  `app.routes.ts`
438
715
 
@@ -472,9 +749,9 @@ export const routes: Routes = [
472
749
  ];
473
750
  ```
474
751
 
475
- > 💡 On charge donc `welcome.routes.ts` (et non plus `welcome.module.ts`) :
752
+ > 💡 So we load `welcome.routes.ts` (and no longer `welcome.module.ts`):
476
753
  > `loadChildren: () => import('./modules/welcome/welcome.routes').then((m) => m.welcome_routes)`
477
- > au lieu de `import('./modules/welcome/welcome.module').then((m) => m.WelcomeModule)`.
754
+ > instead of `import('./modules/welcome/welcome.module').then((m) => m.WelcomeModule)`.
478
755
 
479
756
  `welcome.routes.ts`
480
757
 
@@ -522,47 +799,56 @@ export const inscription_routes: Routes = [
522
799
  ];
523
800
  ```
524
801
 
525
- > 💡 Vous pouvez aussi charger paresseusement (`lazy-load`) un composant :
802
+ > 💡 You can also lazy-load a component:
526
803
  >
527
804
  > ```ts
528
805
  > { path: 'list', loadComponent: () => import('./demande-list-page/demande-list-page.component').then((m) => m.DemandeListPageComponent) },
529
806
  > ```
530
807
 
531
- ## Création d'un composant réutilisable
532
-
533
- > ℹ️ Créer un composant réutilisable en Angular n'est pas difficile mais pour qu'il soit adapté à
534
- > prestations-ng, c'est une autre affaire. Il va falloir respecter certaines règles, sans quoi, ça ne
535
- > fonctionnera pas correctement.
536
-
537
- ### Exemple avec foehn-input-date de prestations-ng
538
-
539
- Votre composant doit :
540
-
541
- 1. `selector` devrait commencer par `"app-..."` pour éviter d'éventuels conflits de nommage
542
- 2. avoir un `providers`
543
- 3. étendre `FoehnInputComponent` et vous devez lui préciser votre modèle de données
544
- 4. répartir les attributs de votre modèle de données dans des variables publiques utilisées dans
545
- votre HTML
546
- 5. implémenter une fonction `update` (ici ce sera `updateDate`) qui fera appel à `updateNgModel` pour
547
- maintenir la synchronisation de votre modèle de données avec votre page
548
- 6. implémenter une fonction `handleUserInput` qui fera appel à `handleChange` pour continuer à
549
- notifier le parent des changements de comportement de votre composant
550
- 7. implémenter une fonction `onModelChange` qui vous permettra d'initialiser correctement les
551
- variables publiques correspondant à votre modèle
552
- 8. implémenter une fonction `getValidValue` afin de reconstruire votre modèle de données avant de le
553
- retransmettre à votre page et retourner `null` si tous les attributs de votre objet sont vides (ça
554
- c'est pour que Java soit content)
555
-
556
- > 🚨 Points **standalone / signals** à respecter :
808
+ ## Creating a reusable component
809
+
810
+ > ℹ️ Creating a reusable component in Angular isn't difficult, but making it fit prestations-ng is
811
+ > another matter. Some rules must be respected, otherwise it won't work properly.
812
+
813
+ ### Example with foehn-input-date of prestations-ng
814
+
815
+ Your component must:
816
+
817
+ 1. `selector` should start with `"app-..."` to avoid possible naming conflicts
818
+ 2. have a `providers`
819
+ 3. extend `FoehnInputComponent`, to which you must give your data model
820
+ 4. spread the attributes of your data model in public **linked signals** (`linkedSignal()`) used
821
+ in your HTML: they follow the model of your page, and your sub-components change them
822
+ 5. implement an `update` function (here it will be `updateDate`) calling `updateNgModel` to
823
+ keep your data model synchronized with your page
824
+ 6. implement a `handleUserInput` function calling `handleChange` to keep
825
+ notifying the parent of the behavior changes of your component
826
+ 7. not override the `onModelChange` function for your linked signals, which already follow the
827
+ model: override it only to act on a new model of your page (e.g. to normalize it)
828
+ 8. implement a `getValidValue` function to rebuild your data model before sending it
829
+ back to your page, and return `null` if all the attributes of your object are empty (this
830
+ is to keep Java happy), once your model is known (`model_ !== undefined`): it is once the model of
831
+ your page has had a value to display, so that a model without any value (e.g. `[]`) is never
832
+ replaced by `null` without an input of the user
833
+
834
+ > 🚨 **standalone / signals** points to respect:
557
835
  >
558
- > - **Pas de `multi: true`** dans le `providers` (retiré depuis la migration standalone).
559
- > - Les `imports` du composant se déclarent **directement** dans le décorateur `@Component`. Chaque
560
- > composant charge ce dont il a besoin (voir `foehn-input-date` dans ce projet).
836
+ > - **No `multi: true`** in the `providers` (removed since the standalone migration).
837
+ > - The `imports` of the component are declared **directly** in the `@Component` decorator. Each
838
+ > component loads what it needs (see `foehn-input-date` in this project).
839
+ > - The state displayed by the component is held in **linked signals** (point 4), derived from the
840
+ > model: a plain field would not be displayed without zone.js, and a `signal()` filled by
841
+ > `onModelChange` (called by an `effect()`) would follow the model only at the next change
842
+ > detection.
843
+ > - `updateNgModel()` receives a **new** object or array, never the model modified in place: the
844
+ > model is a signal, which ignores the same object, so no `modelChange` would be emitted and the
845
+ > page would never get the change. `patchNgModel()` writes a field of the model, or an item of a
846
+ > list, in a new model (see "Editing an object field by field" and the list of vehicles below).
561
847
 
562
848
  `input-date.component.ts`
563
849
 
564
850
  ```ts
565
- import { Component, forwardRef } from '@angular/core';
851
+ import { Component, forwardRef, linkedSignal } from '@angular/core';
566
852
 
567
853
  import { FoehnInputComponent } from '../foehn-input/foehn-input.component';
568
854
  import { FoehnInputNumberComponent } from '../foehn-input/foehn-input-number.component';
@@ -570,7 +856,7 @@ import { FoehnValidationAlertsComponent } from '../foehn-validation-alerts/foehn
570
856
  import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
571
857
 
572
858
  @Component({
573
- // point (1) : dans votre prestation, le selector sera plutôt 'app-...'
859
+ // point (1): in your prestation, the selector will rather be 'app-...'
574
860
  selector: 'app-input-date',
575
861
  templateUrl: './input-date.component.html',
576
862
  // point (2)
@@ -578,10 +864,10 @@ import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
578
864
  {
579
865
  provide: FoehnInputComponent,
580
866
  useExisting: forwardRef(() => InputDateComponent),
581
- // ⚠️ plus de `multi: true` en standalone
867
+ // ⚠️ no more `multi: true` in standalone
582
868
  },
583
869
  ],
584
- // les imports se déclarent directement ici : chaque composant charge ce dont il a besoin
870
+ // the imports are declared directly here: each component loads what it needs
585
871
  imports: [
586
872
  FoehnValidationAlertsComponent,
587
873
  FoehnInputNumberComponent,
@@ -589,12 +875,25 @@ import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
589
875
  ],
590
876
  })
591
877
  export class InputDateComponent extends FoehnInputComponent<number[]> {
592
- // point (3) : extends FoehnInputComponent<number[]>
593
-
594
- // point (4) : les attributs de votre modèle répartis en variables publiques
595
- day: string;
596
- month: string;
597
- year: string;
878
+ // point (3): extends FoehnInputComponent<number[]>
879
+
880
+ // point (4): the attributes of your model spread in public linked signals. A new model of your
881
+ // page resets them, a model too short to hold a date keeps them (previous value).
882
+ readonly day = linkedSignal<number[] | null | undefined, string | null>({
883
+ source: this.model,
884
+ computation: (value, previous) =>
885
+ this.getDatePart(value, 2, previous?.value),
886
+ });
887
+ readonly month = linkedSignal<number[] | null | undefined, string | null>({
888
+ source: this.model,
889
+ computation: (value, previous) =>
890
+ this.getDatePart(value, 1, previous?.value),
891
+ });
892
+ readonly year = linkedSignal<number[] | null | undefined, string | null>({
893
+ source: this.model,
894
+ computation: (value, previous) =>
895
+ this.getDatePart(value, 0, previous?.value),
896
+ });
598
897
 
599
898
  // point (5)
600
899
  updateDate(): void {
@@ -612,25 +911,14 @@ export class InputDateComponent extends FoehnInputComponent<number[]> {
612
911
  }
613
912
  }
614
913
 
615
- // point (7)
616
- override onModelChange(value: number[]): void {
617
- if (value && value.length > 2) {
618
- this.year = this.toString(value[0]);
619
- this.month = this.toString(value[1]);
620
- this.day = this.toString(value[2]);
621
- } else if (!value) {
622
- this.year = null;
623
- this.month = null;
624
- this.day = null;
625
- }
626
- }
914
+ // point (7): no onModelChange(), the linked signals of point (4) already follow the model
627
915
 
628
916
  // point (8)
629
917
  getValidValue(): number[] | null | undefined {
630
918
  if (
631
- this.isEmpty(this.day) &&
632
- this.isEmpty(this.month) &&
633
- this.isEmpty(this.year)
919
+ this.isEmpty(this.day()) &&
920
+ this.isEmpty(this.month()) &&
921
+ this.isEmpty(this.year())
634
922
  ) {
635
923
  if (this.model_ !== undefined) {
636
924
  return null;
@@ -640,26 +928,43 @@ export class InputDateComponent extends FoehnInputComponent<number[]> {
640
928
  }
641
929
 
642
930
  return [
643
- this.toNumber(this.year),
644
- this.toNumber(this.month),
645
- this.toNumber(this.day),
931
+ this.toNumber(this.year()),
932
+ this.toNumber(this.month()),
933
+ this.toNumber(this.day()),
646
934
  ];
647
935
  }
648
936
 
649
937
  // ...code
938
+
939
+ private getDatePart(
940
+ value: number[] | null | undefined,
941
+ index: number,
942
+ previous: string | null | undefined,
943
+ ): string | null {
944
+ if (value && value.length > 2) {
945
+ return this.toString(value[index]);
946
+ }
947
+ return value ? (previous ?? null) : null;
948
+ }
650
949
  }
651
950
  ```
652
951
 
653
- Chaque `foehn-input-*` utilisé dans votre vue doit :
952
+ > 💡 A field that only reads a property of the model can use the short form, e.g.
953
+ > `readonly street = linkedSignal(() => this.model()?.street ?? null);` (see `foehn-input-address`).
954
+ > It resets the field at every new model: use the form `{ source, computation }`, as above, when a
955
+ > field must keep its value on a partial model.
956
+
957
+ Each `foehn-input-*` used in your view must:
654
958
 
655
- 1. avoir un `id` qui concatène l'appel à la fonction `buildId()` et le nom de l'attribut de votre objet
656
- 2. avoir un `name` qui concatène l'input **signal** `name()` et le nom de l'attribut de votre objet
657
- 3. avoir un `label`
658
- 4. utiliser votre variable publique comme model en double-binding (banana in the box)
659
- 5. faire appel à `updateDate()` lors du déclenchement de l'événement `(modelChange)`
660
- 6. faire appel à `handleUserInput()` lors du déclenchement de l'événement `(userInput)`
959
+ 1. have an `id` concatenating the call to the `buildId()` function and the name of the attribute of your object
960
+ 2. have a `name` concatenating the **signal** input `name()` and the name of the attribute of your object
961
+ 3. have a `label`
962
+ 4. use your public signal as model in two-way binding (banana in the box): `[(model)]="day"`
963
+ reads and writes the signal (without the parentheses)
964
+ 5. call `updateDate()` when the `(modelChange)` event is triggered
965
+ 6. call `handleUserInput()` when the `(userInput)` event is triggered
661
966
 
662
- > 💡 `name` est désormais un **input signal**. On l'invoque : `name() + '_day'` (et non plus
967
+ > 💡 `name` is now an **input signal**. You call it: `name() + '_day'` (and no longer
663
968
  > `name + '_day'`).
664
969
 
665
970
  `input-date.component.html`
@@ -702,20 +1007,138 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
702
1007
  />
703
1008
  ```
704
1009
 
705
- ### Afficher la validation globale du composant
1010
+ ### Editing an object field by field
1011
+
1012
+ `foehn-input-date` **transforms** its model: its three text fields hold values the `number[]` can't
1013
+ (a day without its month), so each of them is a linked signal, and `getValidValue()` builds the
1014
+ model from them.
1015
+
1016
+ A component which **edits an object as is**, each field of the object bound to one of its
1017
+ `foehn-input-*` (e.g. a section of the form with a dozen fields), doesn't spread the object in
1018
+ signals: it reads its `model()`, and writes each field with `patchNgModel(path, value)`, which
1019
+ gives a new object to `updateNgModel()`.
1020
+
1021
+ ```ts
1022
+ export class Owner {
1023
+ lastName: string | null = null;
1024
+ address = new OwnerAddress();
1025
+ }
1026
+
1027
+ export class OwnerAddress {
1028
+ street: string | null = null;
1029
+ }
1030
+ ```
1031
+
1032
+ `owner-input.component.ts`
1033
+
1034
+ ```ts
1035
+ export class OwnerInputComponent extends FoehnInputComponent<Owner> {
1036
+ handleUserInput(): void {
1037
+ this.handleChange(this.model() ?? null);
1038
+ }
1039
+
1040
+ // The owner patchNgModel() starts from as long as the page gives none (protected: after the
1041
+ // public members, as @typescript-eslint/member-ordering requires)
1042
+ protected override emptyModel(): Owner {
1043
+ return new Owner();
1044
+ }
1045
+ }
1046
+ ```
1047
+
1048
+ `owner-input.component.html`
1049
+
1050
+ ```html
1051
+ <foehn-input-text
1052
+ [id]="buildId() + '_lastName'"
1053
+ [name]="name() + '.lastName'"
1054
+ [label]="'owner.last-name' | fromDictionary"
1055
+ [model]="model()?.lastName"
1056
+ (modelChange)="patchNgModel(['lastName'], $event)"
1057
+ (userInput)="handleUserInput()"
1058
+ />
1059
+ <foehn-input-text
1060
+ [id]="buildId() + '_street'"
1061
+ [name]="name() + '.address.street'"
1062
+ [label]="'owner.street' | fromDictionary"
1063
+ [model]="model()?.address.street"
1064
+ (modelChange)="patchNgModel(['address', 'street'], $event)"
1065
+ (userInput)="handleUserInput()"
1066
+ />
1067
+ ```
1068
+
1069
+ - `patchNgModel()` copies the objects along the path and keeps the others, and gives the new
1070
+ object to `updateNgModel()`. The same value changes nothing, so no `modelChange` is emitted.
1071
+ - With `strictTemplates`, TypeScript checks the path and the type of the value (`$event`).
1072
+ - `emptyModel()` gives the object `patchNgModel()` starts from as long as the page gives none: a
1073
+ component whose model is always given doesn't override it. Without one, `patchNgModel()`
1074
+ throws, as it does when an object of the path is `null` or `undefined`: hence the class `Owner`
1075
+ creating its `address`.
1076
+ - Several fields at once: `updateNgModel()` with a new object of the class, e.g.
1077
+ `Object.assign(new Owner(), this.model(), { lastName, firstName })`. A spread
1078
+ (`{ ...this.model(), lastName }`) gives a plain object, whereas `patchNgModel()` keeps the class
1079
+ of the objects it copies.
1080
+ - A rule applied at each write (e.g. fields emptied according to another one, a total saved with
1081
+ the object): override `updateNgModel()`, and give `super.updateNgModel()` the corrected object,
1082
+ e.g. with `ObjectPathHelper.patch()`. `patchNgModel()` goes through it, as every other write
1083
+ (see `foehn-input-number`). A value only displayed is rather a `computed()` reading `model()`.
1084
+ - No linked signal and no `getValidValue()`: the component keeps no state of its own, each change
1085
+ goes at once to the model, which the template reads again, and the fields it doesn't display
1086
+ (an id, a version) are kept, as no object is rebuilt by hand. An object whose fields are emptied
1087
+ stays an object, its fields `null`.
1088
+ - When the backend expects `null` for an emptied object (point 8, e.g. an optional object
1089
+ validated by `@Valid`, whose required fields would otherwise be reported), apply it at each
1090
+ write, in the override of `updateNgModel()`:
1091
+
1092
+ ```ts
1093
+ override updateNgModel(value: Owner | null): void {
1094
+ if (ObjectHelper.hasAnyValue(value)) {
1095
+ super.updateNgModel(value);
1096
+ } else if (this.model_ !== undefined) {
1097
+ super.updateNgModel(null);
1098
+ }
1099
+ }
1100
+ ```
1101
+
1102
+ As in point 8, `null` only once the model is known: a field correcting the model given by
1103
+ the page (e.g. `''` replaced by `null`) also emits `modelChange`, and an object without any
1104
+ value given by the page must not be replaced by `null` without an input of the user.
1105
+
1106
+ ### Wrapping a single component
1107
+
1108
+ A component which wraps a single `foehn-*` component, to which it gives its whole model (e.g. a
1109
+ `foehn-input-address` or a `foehn-checkbox` with the label, the help or the elements of your
1110
+ prestation), passes its model through, without a copy:
1111
+
1112
+ ```html
1113
+ <!-- ... with its name, its label, its elements... -->
1114
+ <foehn-input-address
1115
+ [model]="model()"
1116
+ (modelChange)="updateNgModel($event)"
1117
+ (userInput)="handleChange($event)"
1118
+ />
1119
+ ```
1120
+
1121
+ - No copy of the model, in a field or a `linkedSignal()`: the wrapped component already writes a
1122
+ new value.
1123
+ - No `[(model)]="model"`: the two-way binding writes the model with `set()`, which bypasses
1124
+ `updateNgModel()` (`model_`, the model of a disabled component left alone).
1125
+ - A rule applied at each write: override `updateNgModel()`, as for an object edited field by
1126
+ field.
1127
+
1128
+ ### Displaying the global validation of the component
706
1129
 
707
- - Il faut ajouter dans la partie HTML de votre composant le code décrit ci-dessous
708
- - Remonter une erreur correspondant au `name` de votre composant lorsque celui-ci est utilisé dans
709
- votre page de formulaire.
1130
+ - Add the code below in the HTML part of your component
1131
+ - Return an error matching the `name` of your component when it is used in
1132
+ your form page.
710
1133
 
711
- > 💡 Points **signals** à noter dans ce template :
1134
+ > 💡 **signals** points to note in this template:
712
1135
  >
713
- > - `@if` remplace `*ngIf` et les attributs du composant sont des signaux : on les invoque
1136
+ > - `@if` replaces `*ngIf`, and the attributes of the component are signals: you call them
714
1137
  > (`label()`, `required()`, `isLabelSrOnly()`, `hideNotRequiredExtraLabel()`, `helpText()`).
715
- > - `[ngClass]` est remplacé par des bindings `[class.xxx]="..."`.
1138
+ > - `[ngClass]` is replaced by `[class.xxx]="..."` bindings.
716
1139
 
717
1140
  ```html
718
- <!-- (obligatoire) Affichera une barre verticale rouge sur l'entier du composant -->
1141
+ <!-- (mandatory) Displays a red vertical bar on the whole component -->
719
1142
  <div
720
1143
  class="form-group"
721
1144
  [class.has-danger]="hasErrorsToDisplay()"
@@ -723,12 +1146,12 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
723
1146
  [attr.id]="buildId('Container')"
724
1147
  tabindex="-1"
725
1148
  >
726
- <!-- (obligatoire) Permet de regrouper vos champs pour une validation globale -->
1149
+ <!-- (mandatory) Groups your fields for a global validation -->
727
1150
  <fieldset
728
1151
  [attr.aria-describedby]="getDescribedBy()"
729
1152
  [attr.aria-invalid]="hasErrorsToDisplay() || null"
730
1153
  >
731
- <!-- (facultatif) Seulement si vous souhaitez afficher un label/legend global à votre composant -->
1154
+ <!-- (optional) Only if you want to display a global label/legend for your component -->
732
1155
  @if (!!label()) {
733
1156
  <legend
734
1157
  [class.visually-hidden]="isLabelSrOnly()"
@@ -743,10 +1166,10 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
743
1166
  </legend>
744
1167
  }
745
1168
 
746
- <!-- (obligatoire) -->
1169
+ <!-- (mandatory) -->
747
1170
  <foehn-validation-alerts [component]="this" />
748
1171
 
749
- <!-- (facultatif) Seulement si vous souhaitez pouvoir afficher un helpText global au composant -->
1172
+ <!-- (optional) Only if you want to be able to display a global helpText for the component -->
750
1173
  @if (helpText()) {
751
1174
  <small
752
1175
  [attr.id]="buildId() + 'Help'"
@@ -755,69 +1178,70 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
755
1178
  ></small>
756
1179
  }
757
1180
 
758
- <!-- ...vos foehn-input-* ici -->
1181
+ <!-- ...your foehn-input-* here -->
759
1182
  </fieldset>
760
1183
  </div>
761
1184
  ```
762
1185
 
763
- ### Éviter des problèmes d'affichage d'erreurs dans une boucle `@for`
1186
+ ### Avoiding error display problems in a `@for` loop
764
1187
 
765
- > ⚠️ Ne pas oublier de mettre un `track` avec un identifiant unique dans la boucle `@for` sinon la
766
- > validation ne s'affichera pas. Quand un identifiant unique tel que `id` n'est pas possible, tracker
767
- > par objet ou, en dernier recours, `track $index`.
1188
+ > ⚠️ Track the rows of the `@for` loop by `$index`, the index their fields are named with,
1189
+ > otherwise the validation is displayed on the wrong row once an item is removed or the list sorted
1190
+ > (`require-track-index` reports it). Never by object a list of the form whose rows edit their item
1191
+ > (see "Binding the fields of the form").
768
1192
 
769
- > ℹ️ Dans une boucle `@for` d'Angular avec un composant `FoehnInputComponent`, si vous validez votre
770
- > formulaire, les erreurs remontées sont synchronisées avec l'index de vos composants répétés dans la
771
- > boucle.
1193
+ > ℹ️ In an Angular `@for` loop with a `FoehnInputComponent` component, if you validate your
1194
+ > form, the errors returned are synchronized with the index of your components repeated in the
1195
+ > loop.
772
1196
  >
773
- > **Scénario :** Dans votre liste, lorsque vous supprimez un composant qui contient des erreurs à
774
- > l'index 0 (par ex.) et que le composant suivant (index 1) n'a pas d'erreur ou pas les mêmes
775
- > erreurs, alors ce dernier se retrouve avec les erreurs du composant fraîchement supprimé à
776
- > l'index 0.
1197
+ > **Scenario:** In your list, when you remove a component that has errors at
1198
+ > index 0 (for example) and the next component (index 1) has no errors or not the same
1199
+ > errors, then the latter ends up with the errors of the component just removed at
1200
+ > index 0.
777
1201
  >
778
- > **Explication :** Ce phénomène est dû au fait que les erreurs remontées par GESDEM ne se
779
- > rafraîchissent que lors de la demande de sauvegarde des données. Du coup, le composant supprimé à
780
- > l'index 0 est remplacé par celui à l'index 1 mais les erreurs à l'index 0, elles, existent toujours
781
- > et se reportent donc sur le composant venant de l'index 1.
1202
+ > **Explanation:** This happens because the errors returned by GESDEM are only
1203
+ > refreshed when the data is saved. So the component removed at
1204
+ > index 0 is replaced by the one at index 1, but the errors at index 0 still exist
1205
+ > and are therefore carried over to the component coming from index 1.
782
1206
 
783
- Voici la bonne pratique à mettre en place pour palier à ces problèmes d'affichage d'erreurs dans une
784
- boucle `@for`.
1207
+ Here is the good practice to put in place to work around these error display problems in a
1208
+ `@for` loop.
785
1209
 
786
- Lorsque vous supprimez un élément dans votre liste, vous devez appeler une méthode se trouvant dans
787
- votre `AbstractPageComponent`. Cette méthode contiendra le code suivant :
1210
+ When you remove an item from your list, you must call a method of
1211
+ your `AbstractPageComponent`. This method will contain the following code:
788
1212
 
789
1213
  ```ts
790
1214
  /*
791
1215
  * if an inventory item that was in error is removed, this prevents the error to be displayed
792
1216
  * to the next item that has taken it's index
793
1217
  */
794
- this._gesdemService.validate(this.form).pipe(first()).subscribe();
1218
+ this._gesdemService.validate(this.form()).pipe(first()).subscribe();
795
1219
  ```
796
1220
 
797
- Voici un exemple de page de formulaire contenant cette méthode (1) :
1221
+ Here is an example of a form page containing this method (1):
798
1222
 
799
- > 💡 Plus de `constructor` : on fait de l'**inject**. Les dépendances de `AbstractPageComponent`
800
- > (dont `_dictionaryService` et `_gesdemService`) sont déjà injectées dans la classe abstraite. Pour
801
- > vos propres dépendances, utilisez `inject()`.
1223
+ > 💡 No more `constructor`: we use **inject**. The dependencies of `AbstractPageComponent`
1224
+ > (including `_dictionaryService` and `_gesdemService`) are already injected in the abstract class. For
1225
+ > your own dependencies, use `inject()`.
802
1226
 
803
1227
  ```ts
804
1228
  @Component({
805
- templateUrl: './votre-page.component.html',
1229
+ templateUrl: './your-page.component.html',
806
1230
  imports: [
807
- // ... vos composants foehn-*
1231
+ // ... your foehn-* components
808
1232
  ],
809
1233
  })
810
- export class VotrePageComponent
1234
+ export class YourPageComponent
811
1235
  extends AbstractPageComponent<BusinessForm>
812
1236
  implements OnInit
813
1237
  {
814
- // vos propres dépendances : inject() au lieu du constructor
1238
+ // your own dependencies: inject() instead of the constructor
815
1239
  private readonly metaService = inject(MetaService);
816
1240
 
817
1241
  ngOnInit(): void {
818
1242
  super.ngOnInit();
819
1243
  this.setPageTitle(
820
- this._dictionaryService.getKeySync('votre-page.title'),
1244
+ this._dictionaryService.getKeySync('your-page.title'),
821
1245
  );
822
1246
  }
823
1247
 
@@ -831,17 +1255,37 @@ export class VotrePageComponent
831
1255
  * if an inventory item that was in error is removed, this prevents the error to be displayed
832
1256
  * to the next item that has taken it's index
833
1257
  */
834
- this._gesdemService.validate(this.form).pipe(first()).subscribe();
1258
+ this._gesdemService.validate(this.form()).pipe(first()).subscribe();
835
1259
  }
836
1260
  }
837
1261
  ```
838
1262
 
839
- Il ne tient qu'à vous de décider comment appeler cette méthode lors de la suppression de l'élément de
840
- votre liste.
1263
+ It's up to you to decide how to call this method when the item is removed from
1264
+ your list.
841
1265
 
842
- Voici une manière élégante de gérer vos listes d'éléments :
1266
+ A page handling the errors itself (see "Manual handling" in "Form validation") and keeping those of the server
1267
+ until its next save, e.g. a back office, has no validation to call: when it removes an item, it renumbers the errors
1268
+ with `removeListItemErrors()` of `ValidationHandlerService`. The errors of the removed item are dropped, and those of
1269
+ the following items take the new index of their item, the items of their nested lists included
1270
+ (`FormErrorHelper.withoutListItem()` does the same on an array of errors):
843
1271
 
844
- - Structure des dossiers et fichiers
1272
+ ```ts
1273
+ private readonly validationHandlerService = inject(ValidationHandlerService);
1274
+
1275
+ removeExchange(hearingIndex: number, exchangeIndex: number): void {
1276
+ // ... remove the exchange from the model, in a new array
1277
+ this.validationHandlerService.removeListItemErrors(
1278
+ `hearings[${hearingIndex}].exchanges[${exchangeIndex}]`,
1279
+ );
1280
+ }
1281
+ ```
1282
+
1283
+ No component of the library calls it: call it once per removal, and not besides a code of yours renumbering the
1284
+ errors already, or they would move twice.
1285
+
1286
+ Here is an elegant way to handle your lists of items:
1287
+
1288
+ - Structure of the folders and files
845
1289
 
846
1290
  ```text
847
1291
  demande-page/
@@ -858,7 +1302,18 @@ demande-page/
858
1302
 
859
1303
  **vehicule-item**
860
1304
 
861
- `vehicule-item.component.html` contient le bouton pour la suppression de l'élément dans la liste (1).
1305
+ A vehicle of the list is a `Vehicule` of your form, here with a brand and a plate number:
1306
+
1307
+ ```ts
1308
+ export class Vehicule {
1309
+ brand: string | null = null;
1310
+ plateNumber: string | null = null;
1311
+ }
1312
+ ```
1313
+
1314
+ `vehicule-item.component.html` binds each field of the vehicle to its model, and writes it with
1315
+ `patchNgModel()` (1) (see "Editing an object field by field"). It contains the button removing the
1316
+ item from the list (2).
862
1317
 
863
1318
  ```html
864
1319
  <div
@@ -871,11 +1326,37 @@ demande-page/
871
1326
  <foehn-validation-alerts [component]="this" />
872
1327
 
873
1328
  <div class="row d-flex align-items-end vehicule-infos">
874
- <!-- ... vos composants foehn-input-* -->
1329
+ <div class="col-md-5">
1330
+ <!-- (1) the name of the field in the form, as in the errors of the backend: vehicules[0].brand -->
1331
+ <foehn-input-text
1332
+ [id]="buildId() + '_brand'"
1333
+ [name]="name() + '.brand'"
1334
+ [label]="'demande-page.vehicule-brand' | fromDictionary"
1335
+ [model]="model()?.brand"
1336
+ (modelChange)="patchNgModel(['brand'], $event)"
1337
+ (userInput)="handleUserInput()"
1338
+ [required]="true"
1339
+ />
1340
+ </div>
1341
+ <div class="col-md-5">
1342
+ <foehn-input-text
1343
+ [id]="buildId() + '_plateNumber'"
1344
+ [name]="name() + '.plateNumber'"
1345
+ [label]="'demande-page.vehicule-plate-number' | fromDictionary"
1346
+ [model]="model()?.plateNumber"
1347
+ (modelChange)="patchNgModel(['plateNumber'], $event)"
1348
+ (userInput)="handleUserInput()"
1349
+ [required]="true"
1350
+ />
1351
+ </div>
875
1352
 
876
1353
  <div class="col-md-2 mt-md-0 mt-xs-2">
877
- <button class="btn btn-danger" (click)="removeVehicule()">
878
- <!-- (1) -->
1354
+ <button
1355
+ class="btn btn-danger"
1356
+ type="button"
1357
+ (click)="removeVehicule()"
1358
+ >
1359
+ <!-- (2) -->
879
1360
  {{ 'demande-page.vehicule-remove' | fromDictionary }}
880
1361
  </button>
881
1362
  </div>
@@ -883,10 +1364,11 @@ demande-page/
883
1364
  </div>
884
1365
  ```
885
1366
 
886
- `vehicule-item.component.ts` contient la fonction de suppression qui va remonter l'événement à son
887
- parent (la liste des éléments).
1367
+ `vehicule-item.component.ts` has nothing to do for its fields: `patchNgModel()` gives the list a
1368
+ new vehicle at each change, which keeps the fields the component doesn't display (e.g. an id). It
1369
+ contains the removal function, which sends the event up to its parent, the list of items (3).
888
1370
 
889
- > 💡 `@Output() + EventEmitter` sont remplacés par la fonction `output()`.
1371
+ > 💡 `@Output() + EventEmitter` are replaced by the `output()` function.
890
1372
 
891
1373
  ```ts
892
1374
  @Component({
@@ -900,28 +1382,36 @@ parent (la liste des éléments).
900
1382
  ],
901
1383
  imports: [
902
1384
  FoehnValidationAlertsComponent,
903
- // ... vos foehn-input-*
1385
+ FoehnInputTextComponent,
904
1386
  SdkDictionaryPipe,
905
1387
  ],
906
1388
  })
907
1389
  export class VehiculeItemComponent extends FoehnInputComponent<Vehicule> {
908
1390
  readonly removedVehicule = output<void>();
909
1391
 
1392
+ handleUserInput(): void {
1393
+ this.handleChange(this.model() ?? null);
1394
+ }
1395
+
910
1396
  removeVehicule(): void {
1397
+ // (3)
911
1398
  this.removedVehicule.emit();
912
1399
  }
913
-
914
- // ...code
915
1400
  }
916
1401
  ```
917
1402
 
1403
+ > 💡 The list always gives a vehicle: no `emptyModel()` needed. A vehicle the user empties stays in
1404
+ > the list, with its errors, until it is removed with its button.
1405
+
918
1406
  **vehicules-list**
919
1407
 
920
- `vehicules-list.component.html` contient votre boucle `@for` (1) et votre composant répétable (2) qui
921
- devra lui aussi remonter l'événement.
1408
+ `vehicules-list.component.html` contains your `@for` loop (1) and your repeatable component (2), which
1409
+ must also send the event up.
922
1410
 
923
- > ⚠️ Dans la boucle `@for` ne pas oublier de mettre un `track` (identifiant unique) sinon la
924
- > validation ne s'affichera pas. Ici nous trackons par exemple avec `vehicule.id`.
1411
+ > ⚠️ In the `@for` loop, track the rows by `$index`, as here: the names of the fields are built
1412
+ > with it, and the validation would otherwise be displayed on the wrong row. Never the item
1413
+ > itself (`track vehicule`): each change replaces it with a new vehicle, so its row would be created
1414
+ > again at each input, and the field being edited would lose the focus.
925
1415
 
926
1416
  ```html
927
1417
  <div
@@ -954,30 +1444,35 @@ devra lui aussi remonter l'événement.
954
1444
  ></small>
955
1445
  }
956
1446
 
957
- <!-- (1) votre boucle @for + track (identifiant unique) -->
958
- @for (vehicule of vehicules; track vehicule.id; let i = $index) {
959
- <!-- (2) votre composant réutilisable -->
1447
+ <!-- (1) your @for loop over the model + track -->
1448
+ @for (vehicule of model(); track $index; let i = $index) {
1449
+ <!-- (2) your reusable component -->
960
1450
  <app-vehicule-item
961
1451
  [name]="name() + '[' + i + ']'"
962
- [(model)]="vehicule"
963
- (modelChange)="updateVehiculesList($event, i)"
964
- (userInput)="handleUserInput($event, i)"
1452
+ [model]="vehicule"
1453
+ (modelChange)="patchNgModel([i], $event)"
1454
+ (userInput)="handleUserInput()"
965
1455
  (removedVehicule)="handleRemovedVehicule(i)"
966
1456
  />
967
1457
  }
968
1458
 
969
- <button class="btn btn-primary mt-2" (click)="addVehicule()">
1459
+ <button class="btn btn-primary mt-2" type="button" (click)="addVehicule()">
970
1460
  {{ 'demande-page.vehicule-add' | fromDictionary }}
971
1461
  </button>
972
1462
  </div>
973
1463
  ```
974
1464
 
975
- > 💡 Le `name` est un input signal : `[name]="name() + '[' + i + ']'"` (et non plus
1465
+ > 💡 The `name` is an input signal: `[name]="name() + '[' + i + ']'"` (and no longer
976
1466
  > `[name]="name + '[' + i + ']'"`).
1467
+ >
1468
+ > 💡 The variable of a `@for` loop can't be modified: the item is passed with `[model]`, and
1469
+ > its `(modelChange)` replaces the item of the list with `patchNgModel([i], $event)`, in a new
1470
+ > list. With `strictTemplates`, TypeScript checks the path `[i]` and the vehicle `$event`. A method
1471
+ > of the list is only needed when it adds something to the replacement of the item.
977
1472
 
978
- `vehicules-list.component.ts` remonte à son tour l'événement (1) au parent (`AbstractPageComponent`)
979
- ainsi que supprimer l'élément de la liste (2). C'est aussi ici que vous pouvez gérer l'ajout d'un
980
- élément (3).
1473
+ `vehicules-list.component.ts` in turn sends the event (1) up to the parent (`AbstractPageComponent`)
1474
+ and removes the item from the list (2). This is also where you can handle the addition of an
1475
+ item (3). Each change writes a new list in the model (4).
981
1476
 
982
1477
  ```ts
983
1478
  @Component({
@@ -996,45 +1491,81 @@ ainsi que supprimer l'élément de la liste (2). C'est aussi ici que vous pouvez
996
1491
  ],
997
1492
  })
998
1493
  export class VehiculesListComponent extends FoehnInputComponent<Vehicule[]> {
999
- readonly removedVehicule = output<void>(); // (1) événement à remonter au parent
1494
+ readonly removedVehicule = output<void>(); // (1) event to send up to the parent
1000
1495
 
1001
- vehicules: Vehicule[] = []; // Tableau contenant vos éléments répétables
1496
+ handleUserInput(): void {
1497
+ const validValue = this.getValidValue(this.model() ?? []);
1498
+ if (typeof validValue !== 'undefined') {
1499
+ this.handleChange(validValue);
1500
+ }
1501
+ }
1002
1502
 
1003
1503
  handleRemovedVehicule(index: number): void {
1004
- // (2) votre fonction de suppression de l'élément ainsi que la transmission de l'évènement
1005
- this.vehicules.splice(index, 1); // suppression de l'élément
1006
- this.getValidValueAndUpdateNgModel(); // Mise à jour de votre modèle
1007
- this.removedVehicule.emit(); // (1) on remonte l'évènement
1504
+ // (2) your function removing the item and sending the event
1505
+ this.updateVehicules(
1506
+ (this.model() ?? []).filter((_vehicule, i) => i !== index),
1507
+ );
1508
+ this.removedVehicule.emit(); // (1) the event is sent up
1008
1509
  }
1009
1510
 
1010
1511
  addVehicule(): void {
1011
- // (3) Gestion de l'ajout d'un élément
1012
- // ...code
1512
+ // (3) Handling of the addition of an item
1513
+ this.updateVehicules([...(this.model() ?? []), new Vehicule()]);
1514
+ }
1515
+
1516
+ // (4) a new list, never the list of the model modified in place (push(), splice(), list[i] = ...)
1517
+ private updateVehicules(vehicules: Vehicule[]): void {
1518
+ const validValue = this.getValidValue(vehicules);
1519
+ if (typeof validValue !== 'undefined') {
1520
+ this.updateNgModel(validValue);
1521
+ }
1522
+ }
1523
+
1524
+ private getValidValue(
1525
+ vehicules: Vehicule[],
1526
+ ): Vehicule[] | null | undefined {
1527
+ if (vehicules.length) {
1528
+ return vehicules;
1529
+ }
1530
+ // An empty list is null once the model is known (point 8 of "Creating a reusable component")
1531
+ return this.model_ !== undefined ? null : undefined;
1013
1532
  }
1014
1533
  }
1015
1534
  ```
1016
1535
 
1017
- > 💡 Plus besoin de définir une `trackByFn` dédiée : la nouvelle syntaxe `@for` utilise directement
1018
- > l'expression `track` (ici `vehicule.id`).
1536
+ > 🚨 Never modify the list of the model, or one of its items, in place and give it back to
1537
+ > `updateNgModel()`: the model is a signal, which ignores the same array. No `modelChange` is
1538
+ > emitted, so the page never gets the change: its `patchForm()` isn't called, and the form, modified
1539
+ > in place, notifies nothing.
1540
+ >
1541
+ > 💡 The list reads its `model()` directly, in the template and in the class: a copy in a
1542
+ > `linkedSignal()` would only duplicate it. The linked signals are for a component transforming its
1543
+ > model, as `foehn-input-date`.
1544
+ >
1545
+ > 💡 No need to define a dedicated `trackByFn` anymore: the new `@for` syntax directly uses
1546
+ > the `track` expression (here `$index`).
1019
1547
 
1020
1548
  **demande-page**
1021
1549
 
1022
- `demande-page.component.html` utilisera votre composant de liste de véhicule (1) et écoutera pour
1023
- l'événement de suppression (2).
1550
+ `demande-page.component.html` uses your vehicle list component (1) and listens to
1551
+ the removal event (2).
1024
1552
 
1025
1553
  ```html
1026
1554
  <foehn-form>
1027
1555
  <!-- ... -->
1028
1556
  <h2>{{ 'demande-page.vehicules' | fromDictionary }}</h2>
1029
1557
 
1558
+ @if (form(); as form) {
1030
1559
  <app-vehicules-list
1031
- [(model)]="form.vehicules"
1560
+ [model]="form.vehicules"
1561
+ (modelChange)="patchForm(['vehicules'], $event)"
1032
1562
  name="vehicules"
1033
1563
  [label]="'demande-page.vehicules-list' | fromDictionary"
1034
1564
  [required]="true"
1035
1565
  (removedVehicule)="handleRemovedVehicule()"
1036
1566
  />
1037
- <!-- (1) Utilisation de votre liste - (2) Appel de la méthode qui sauvegardera les données dans GESDEM afin de rafraîchir les erreurs -->
1567
+ }
1568
+ <!-- (1) Use of your list - (2) Call of the method saving the data in GESDEM to refresh the errors -->
1038
1569
 
1039
1570
  <foehn-navigation
1040
1571
  id="navigation"
@@ -1044,8 +1575,8 @@ l'événement de suppression (2).
1044
1575
  </foehn-form>
1045
1576
  ```
1046
1577
 
1047
- `demande-page.component.ts` se chargera de l'appel à GESDEM afin de re-générer les erreurs du
1048
- formulaire et ainsi rafraîchir l'index.
1578
+ `demande-page.component.ts` calls GESDEM to generate the errors of the
1579
+ form again, and thus refresh the index.
1049
1580
 
1050
1581
  ```ts
1051
1582
  @Component({
@@ -1062,25 +1593,78 @@ export class DemandePageComponent
1062
1593
  * if an inventory item that was in error is removed, this prevents the error to be displayed
1063
1594
  * to the next item that has taken it's index
1064
1595
  */
1065
- this._gesdemService.save(this.form).pipe(first()).subscribe();
1596
+ this._gesdemService.save(this.form()).pipe(first()).subscribe();
1066
1597
  }
1067
1598
  }
1068
1599
  ```
1069
1600
 
1070
- ## Validation du formulaire
1601
+ ## Types of the form fields
1602
+
1603
+ > ℹ️ `AbstractPageComponent` replaces `form` with the JSON sent by the backend, as is: at runtime, a field has
1604
+ > the type of the JSON written from the Java model, whatever its TypeScript type says.
1605
+
1606
+ Give the Java field the type matching the model of the component:
1607
+
1608
+ | Component | TypeScript model | Java field |
1609
+ | ------------------------------------------------------------------ | -------------------- | -------------------------------------- |
1610
+ | `foehn-input-text`, `foehn-input-textarea`, `foehn-input-email`... | `string` | `String` |
1611
+ | `foehn-input-time` | `string` | `String` with `@ValidStringTime` |
1612
+ | `foehn-input-date` | `(number \| null)[]` | `LenientLocalDate` |
1613
+ | `foehn-input-date-time` | `(number \| null)[]` | `LenientLocalDateTime` |
1614
+ | `foehn-boolean-checkbox`, `foehn-boolean-radio` | `boolean` | `Boolean` |
1615
+ | `foehn-input-number` | `string` | `Integer`, `BigDecimal`... (see below) |
1071
1616
 
1072
- > ℹ️ Lors de la sauvegarde de votre formulaire dans GESDEM, l'`AbstractPageComponent` gère pour vous
1073
- > l'affichage éventuel des erreurs.
1617
+ > ⚠️ The model of `foehn-input-number` is a `string`: the component keeps the input as typed (decimal comma,
1618
+ > leading zeros, number of decimals). But the Java field is a number (`Integer`, `BigDecimal`), which is
1619
+ > written as a number in the JSON. The field holds `'0'` after the input of the user, and `0` once the form
1620
+ > comes back from the backend. The same happens with any component whose model is a `string` bound to a Java
1621
+ > field which isn't a `String`.
1622
+
1623
+ Never test such a field by its truthiness (`!!value`, `if (value)`, `value || ...`): `'0'` is true, `0` is
1624
+ false.
1625
+
1626
+ What **not** to do:
1627
+
1628
+ ```ts
1629
+ isAmountFilled(): boolean {
1630
+ // true after the input of '0', false once the form is loaded (0)
1631
+ return !!this.form()?.amount;
1632
+ }
1633
+ ```
1634
+
1635
+ What **to** do:
1636
+
1637
+ ```ts
1638
+ isAmountFilled(): boolean {
1639
+ const amount = this.form()?.amount;
1640
+ return amount !== null && amount !== undefined && amount !== '';
1641
+ }
1642
+
1643
+ getTotal(): number {
1644
+ // Number() converts '12.50' as well as 12.5
1645
+ return Number(this.form()?.amount ?? 0) + Number(this.form()?.fees ?? 0);
1646
+ }
1647
+ ```
1648
+
1649
+ > ⚠️ The values of the elements of `foehn-select` and `foehn-checkbox` must have the type of the Java field:
1650
+ > they are compared to the model with `===`. With `'1'` as value of an element and `1` sent by the backend
1651
+ > (`Integer`), no element is selected anymore once the form is loaded, and the component warns that the saved
1652
+ > value no longer exists in the list.
1653
+
1654
+ ## Form validation
1655
+
1656
+ > ℹ️ When your form is saved in GESDEM, the `AbstractPageComponent` handles the
1657
+ > display of the errors for you.
1074
1658
  >
1075
- > Si par contre vous souhaitez sauvegarder les données ailleurs que dans GESDEM, vous serez confronté
1076
- > à la gestion manuelle de l'affichage des erreurs.
1659
+ > If, however, you want to save the data somewhere else than in GESDEM, you will have to handle
1660
+ > the display of the errors manually.
1077
1661
 
1078
- ### Gestion standard
1662
+ ### Standard handling
1079
1663
 
1080
- > ℹ️ Lors de l'enregistrement de vos données dans GESDEM, l'affichage des erreurs est automatiquement
1081
- > géré pour vous. Cependant, vous devez impérativement respecter certaines règles.
1664
+ > ℹ️ When your data is saved in GESDEM, the display of the errors is handled automatically
1665
+ > for you. However, you must respect some rules.
1082
1666
 
1083
- Prenons un exemple de modèle simple côté front à deux niveaux de profondeur :
1667
+ Let's take an example of a simple front-end model with two levels of depth:
1084
1668
 
1085
1669
  `identification.ts`
1086
1670
 
@@ -1100,44 +1684,52 @@ export class BusinessForm {
1100
1684
  }
1101
1685
  ```
1102
1686
 
1103
- > ⚠️ Le modèle ci-dessus devra impérativement être reflété dans le `name` de vos composants
1104
- > `foehn-input-*` de votre page.
1687
+ > ⚠️ The model above must be reflected in the `name` of the `foehn-input-*`
1688
+ > components of your page.
1105
1689
 
1106
1690
  `page-1.html`
1107
1691
 
1108
1692
  ```html
1693
+ @if (form(); as form) {
1109
1694
  <foehn-input-text
1110
- [(model)]="form.identification.firstName"
1695
+ [model]="form.identification.firstName"
1696
+ (modelChange)="patchForm(['identification', 'firstName'], $event)"
1111
1697
  name="identification.firstName"
1112
1698
  />
1113
- <!-- 2 niveaux de profondeur -->
1699
+ <!-- 2 levels of depth -->
1114
1700
 
1115
1701
  <foehn-input-text
1116
- [(model)]="form.identification.lastName"
1702
+ [model]="form.identification.lastName"
1703
+ (modelChange)="patchForm(['identification', 'lastName'], $event)"
1117
1704
  name="identification.lastName"
1118
1705
  />
1119
1706
 
1120
- <foehn-boolean-checkbox [(model)]="form.acceptCookies" name="acceptCookies" />
1121
- <!-- 1 niveau de profondeur -->
1707
+ <foehn-boolean-checkbox
1708
+ [model]="form.acceptCookies"
1709
+ (modelChange)="patchForm(['acceptCookies'], $event)"
1710
+ name="acceptCookies"
1711
+ />
1712
+ <!-- 1 level of depth -->
1713
+ }
1122
1714
  ```
1123
1715
 
1124
- - Côté back-end, vous pouvez gérer vos erreurs grâce aux annotations (`@NotEmpty`, `@NotNull`, ...),
1125
- et **prestations-be** fera le reste pour vous.
1126
- - Si vous souhaitez remonter une erreur spécifique à un champ de votre formulaire, voici la syntaxe :
1716
+ - On the back-end side, you can handle your errors with the annotations (`@NotEmpty`, `@NotNull`, ...),
1717
+ and **prestations-be** does the rest for you.
1718
+ - If you want to return an error specific to a field of your form, here is the syntax:
1127
1719
 
1128
1720
  ```java
1129
- new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "Le nom est obligatoire si vous ne spécifiez pas de prénom")
1721
+ new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "The last name is required if you don't specify a first name")
1130
1722
  ```
1131
1723
 
1132
- > ⚠️ Le nom de l'erreur doit impérativement correspondre au nom de votre composant dans votre page
1133
- > HTML.
1724
+ > ⚠️ The name of the error must match the name of your component in your HTML
1725
+ > page.
1134
1726
 
1135
- ### Gestion manuelle
1727
+ ### Manual handling
1136
1728
 
1137
1729
  #### Back-end
1138
1730
 
1139
- Côté back-end JAVA, le serveur devra retourner un objet contenant les erreurs du formulaire afin
1140
- d'être compatible avec prestations-ng.
1731
+ On the JAVA back-end side, the server must return an object containing the errors of the form to
1732
+ be compatible with prestations-ng.
1141
1733
 
1142
1734
  ```java
1143
1735
  @Getter
@@ -1151,40 +1743,41 @@ public class PostResponse<T> {
1151
1743
 
1152
1744
  @Builder.Default
1153
1745
  private List<AbstractSdkController.FormError> errors = new ArrayList<>();
1154
- // AbstractSdkController.FormError vient de prestations-be qui est la partie backend de prestations-ng
1746
+ // AbstractSdkController.FormError comes from prestations-be, the backend part of prestations-ng
1155
1747
  }
1156
1748
  ```
1157
1749
 
1158
- Ensuite, ajoutez vos erreurs dans votre modèle avant de le retourner au front-end :
1750
+ Then, add your errors to your model before returning it to the front-end:
1159
1751
 
1160
1752
  ```java
1161
1753
  List<AbstractSdkController.FormError> errors = new ArrayList<>();
1162
- errors.add(new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "Le nom est obligatoire si vous ne spécifiez pas de prénom"));
1754
+ errors.add(new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "The last name is required if you don't specify a first name"));
1163
1755
 
1164
1756
  PostResponse.<MyObject>builder().dto(myObject).errors(errors).build();
1165
1757
  ```
1166
1758
 
1167
1759
  #### Front-end
1168
1760
 
1169
- Côté front-end, comme la validation standard, les noms de vos composants `foehn-input-*` de votre
1170
- page HTML et le nom de vos erreurs devront correspondre.
1761
+ On the front-end side, as for the standard validation, the names of the `foehn-input-*` components of your
1762
+ HTML page and the names of your errors must match.
1171
1763
 
1172
1764
  ```html
1173
1765
  <foehn-input-text
1174
- [(model)]="form.identification.lastName"
1766
+ [model]="form.identification.lastName"
1767
+ (modelChange)="patchForm(['identification', 'lastName'], $event)"
1175
1768
  name="identification.lastName"
1176
1769
  />
1177
1770
  ```
1178
1771
 
1179
- > ⚠️ Au retour de la sauvegarde de vos données, vous allez devoir déclencher manuellement la
1180
- > validation.
1772
+ > ⚠️ When your data has been saved, you will have to trigger the validation
1773
+ > manually.
1181
1774
 
1182
- 1. Dans votre `page.ts`, créez une fonction `handleValidationErrors` pour gérer l'affichage des
1183
- erreurs.
1184
- 2. Cette fonction sera appelée au retour du back-end.
1775
+ 1. In your `page.ts`, create a `handleValidationErrors` function to handle the display of the
1776
+ errors.
1777
+ 2. This function is called when the back-end answers.
1185
1778
 
1186
- > 💡 Point **signals** : plus de `@ViewChild('formWithModels')`. Pour utiliser un composant dans le
1187
- > TypeScript, on utilise un **signal** `viewChild(...)`. On accède ensuite à l'instance en l'invoquant :
1779
+ > 💡 **signals** point: no more `@ViewChild('formWithModels')`. To use a component in the
1780
+ > TypeScript, use a `viewChild(...)` **signal**. Then access the instance by calling it:
1188
1781
  > `this.formWithModels()`.
1189
1782
 
1190
1783
  `page.ts`
@@ -1201,39 +1794,41 @@ import {
1201
1794
  // ...
1202
1795
  })
1203
1796
  export class ... extends AbstractPageComponent<YOUR_MODEL> implements OnInit {
1204
- // point (7 des signaux) : un signal viewChild au lieu de @ViewChild
1797
+ // a viewChild signal instead of @ViewChild
1205
1798
  readonly formWithModels = viewChild(FoehnFormComponent);
1206
1799
 
1207
- // vos propres dépendances via inject()
1800
+ // your own dependencies with inject()
1208
1801
  private readonly httpClient = inject(HttpClient);
1209
1802
 
1210
1803
  ngOnInit(): void {
1211
1804
  super.ngOnInit();
1212
- // Activer l'affichage des erreurs
1805
+ // Enable the display of the errors
1213
1806
  this._validationHandlerService.shouldDisplayErrors(true);
1214
1807
  }
1215
1808
 
1216
- // Fonction de sauvegarde
1809
+ // Save function
1217
1810
  save(): void {
1218
- // Activer l'affichage des erreurs
1811
+ // Enable the display of the errors
1219
1812
  this._validationHandlerService.shouldDisplayErrors(true);
1220
- // Appel au back pour faire votre validation
1813
+ // Call to the back-end to do your validation. The callback modifies no field of the page:
1814
+ // the services of prestations-ng (growl, errors) refresh the display themselves, also
1815
+ // without zone.js. A state of the page modified here should be a signal.
1221
1816
  this.httpClient
1222
- .post<PostResponse>('api_url_ici', votre_objet)
1817
+ .post<PostResponse>('api_url_here', your_object)
1223
1818
  .subscribe((response: PostResponse) => {
1224
1819
  if (!response.errors.length) {
1225
- // On prévient l'utilisateur que tout s'est bien passé
1820
+ // Tell the user that everything went well
1226
1821
  this._growlService.addWithType(
1227
1822
  GrowlType.SUCCESS,
1228
- 'Enregistrement effectué avec succès',
1823
+ 'Saved successfully',
1229
1824
  );
1230
1825
  }
1231
- // Gestion des erreurs au retour du back-end
1826
+ // Handling of the errors returned by the back-end
1232
1827
  this.handleValidationErrors(response.errors); // point (2)
1233
1828
  });
1234
1829
  }
1235
1830
 
1236
- // Affichage des erreurs
1831
+ // Display of the errors
1237
1832
  private handleValidationErrors(errors: ErrorTemplate[]): void {
1238
1833
  // point (1)
1239
1834
  const form = this.formWithModels();
@@ -1251,21 +1846,21 @@ export class ... extends AbstractPageComponent<YOUR_MODEL> implements OnInit {
1251
1846
 
1252
1847
  ```html
1253
1848
  <foehn-form>
1254
- <!-- ... vos composants foehn-input-* -->
1849
+ <!-- ... your foehn-input-* components -->
1255
1850
  </foehn-form>
1256
1851
  ```
1257
1852
 
1258
- ## Validation manuelle d'un composant
1853
+ ## Manual validation of a component
1259
1854
 
1260
- ### Cacher une erreur
1855
+ ### Hiding an error
1261
1856
 
1262
- > ✅ Utiliser la fonction `markAsDirty()` permet de simuler une interaction avec le composant.
1857
+ > ✅ The `markAsDirty()` function simulates an interaction with the component.
1263
1858
  >
1264
- > ℹ️ Permet de cacher l'erreur d'un composant foehn-input en erreur.
1859
+ > ℹ️ Hides the error of a foehn-input component in error.
1265
1860
 
1266
- ### Afficher une erreur
1861
+ ### Displaying an error
1267
1862
 
1268
- > ✅ Utiliser la fonction `markAsPristine()` remet le composant dans son état d'origine comme si
1269
- > aucune interaction n'avait été effectuée.
1863
+ > ✅ The `markAsPristine()` function puts the component back in its original state, as if
1864
+ > no interaction had happened.
1270
1865
  >
1271
- > ℹ️ Permet d'afficher l'erreur d'un composant foehn-input en erreur.
1866
+ > ℹ️ Displays the error of a foehn-input component in error.