@dsivd/prestations-ng 19.2.0-beta.2 → 19.2.0-beta.20

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.
package/GOOD_PRACTICES.md CHANGED
@@ -1,97 +1,105 @@
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
+ - [Zoneless application](good-practices#zoneless_application)
25
+ - [Displaying an asynchronous state](good-practices#displaying_an_asynchronous_state)
26
+ - [Deriving a state from view queries](good-practices#deriving_a_state_from_view_queries)
27
+ - [Acting on the DOM after rendering](good-practices#acting_on_the_dom_after_rendering)
28
+ - [Testing a zoneless component](good-practices#testing_a_zoneless_component)
29
+ - [Routing your pages](good-practices#routing_your_pages)
30
+ - [Simple form](good-practices#simple_form)
31
+ - [Complex form (sub-routes)](good-practices#complex_form__sub-routes_)
32
+ - [Creating a reusable component](good-practices#creating_a_reusable_component)
33
+ - [Example with foehn-input-date of prestations-ng](good-practices#example_with_foehn-input-date_of_prestations-ng)
34
+ - [Displaying the global validation of the component](good-practices#displaying_the_global_validation_of_the_component)
35
+ - [Avoiding error display problems in a `@for` loop](good-practices#avoiding_error_display_problems_in_a__code__for__code__loop)
36
+ - [Types of the form fields](good-practices#types_of_the_form_fields)
37
+ - [Form validation](good-practices#form_validation)
38
+ - [Standard handling](good-practices#standard_handling)
39
+ - [Manual handling](good-practices#manual_handling)
32
40
  - [Back-end](good-practices#back-end)
33
41
  - [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)
42
+ - [Manual validation of a component](good-practices#manual_validation_of_a_component)
43
+ - [Hiding an error](good-practices#hiding_an_error)
44
+ - [Displaying an error](good-practices#displaying_an_error)
37
45
 
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>`).
46
+ > ⚠️ All your HTML pages must have a `<foehn-form>`, and it **can't be
47
+ > conditional** (no `@if` around `<foehn-form>`).
40
48
 
41
49
  ## Documentation
42
50
 
43
51
  - [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
52
  - [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)
53
+ - [prestations-ng (generated doc)](https://dsi-vd.github.io/prestations-ng/generateddoc/)
54
+ - [foehn](https://dsi-vd.github.io/foehn-design-system/components/detail/formulaire-prestation--default.html) (Graphic charter)
47
55
  - [CSS](https://www.w3schools.com/css/default.asp)
48
56
  - [Bootstrap](https://getbootstrap.com/docs/5.3/layout/grid/)
49
57
  - [Flex - Bootstrap](https://getbootstrap.com/docs/5.3/utilities/flex/)
50
58
  - [Flex](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)
51
59
  - [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)
60
+ - [Section elements](https://www.alsacreations.com/article/lire/1376-html5-section-article-nav-header-footer-aside.html) (in French)
53
61
  - [Description list](https://www.w3schools.com/tags/tag_dl.asp)
54
62
  - [RXJS](https://rxjs-dev.firebaseapp.com/)
55
63
 
56
- ## Mise à jour de la librairie
64
+ ## Updating the library
57
65
 
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.
66
+ > ℹ️ 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/)
67
+ > page: you will be notified of the new releases. You will then benefit from the bug fixes,
68
+ > improvements and new features.
61
69
  >
62
- > Prenez le temps de lire le [changelog](CHANGELOG.md) de **prestations-ng** à chaque nouvelle release.
70
+ > Take the time to read the [changelog](CHANGELOG.md) of **prestations-ng** at each new release.
63
71
  >
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.
72
+ > Don't hesitate to open JIRA tickets (PRESTAKIT-xxx) in [PrestaKit (formerly SDK Cyber)](https://issuetracker.etat-de-vaud.ch/outils/issuetracker/browse/PRESTAKIT)
73
+ > to report bugs, or even to suggest improvements in order to
74
+ > [contribute](CONTRIBUTING.md) to the development of prestations-ng.
67
75
 
68
- Mettre à jour la librairie prestations-ng (npm) :
76
+ Update the prestations-ng library (npm):
69
77
 
70
78
  ```bash
71
79
  ng update @dsivd/prestations-ng
72
80
  ```
73
81
 
74
- ## Accessibilité
82
+ ## Accessibility
75
83
 
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.
84
+ > ℹ️ When developing prestations for the State, we must do everything we can to make our web pages
85
+ > as accessible as possible to the general public.
78
86
  >
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.
87
+ > Prestations-ng does a good part of the job for us, but it's up to the developer to make the
88
+ > necessary efforts so that the prestation stays accessible.
81
89
 
82
- ### Structure HTML
90
+ ### HTML structure
83
91
 
84
- > ⚠️ Nous recommandons :
92
+ > ⚠️ We recommend to:
85
93
  >
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>`)
94
+ > - have a single h1 tag (`<h1>`)
95
+ > - respect the hierarchy h1, h2, h3..
96
+ > - group your information in sections (`<section>`) if you have several h2 (`<h2>`)
97
+ > - use the Bootstrap CSS class `col-md-8` to define the width of your form
98
+ > - organize your text with paragraphs (`<p>`)
99
+ > - use the `<dl>`, `<dt>` and `<dd>` tags to display keys / values (see [foehn-recap-section](https://dsi-vd.github.io/prestations-ng/recap))
100
+ > - use [foehn-abbr](https://dsi-vd.github.io/prestations-ng/misc) for the abbreviations whenever possible, and the abbr tag (`<abbr>`) otherwise
93
101
 
94
- Ce qu'il ne faut **pas** faire :
102
+ What **not** to do:
95
103
 
96
104
  ```html
97
105
  <h1>...</h1>
@@ -101,7 +109,7 @@ Ce qu'il ne faut **pas** faire :
101
109
  ... ... ...
102
110
  ```
103
111
 
104
- Ce qu'il **faut** faire :
112
+ What **to** do:
105
113
 
106
114
  ```html
107
115
  <h1>...</h1>
@@ -116,27 +124,27 @@ Ce qu'il **faut** faire :
116
124
  <section>...</section>
117
125
  ```
118
126
 
119
- Quelques attributs HTML utiles :
127
+ Some useful HTML attributes:
120
128
 
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]"`
129
+ - For the images (`<img>`)
130
+ - `title="[explicit text here]"`
131
+ - `alt="[explicit text here]"`
132
+ - For the links (`<a>`)
133
+ - `title="[explicit text here]"`
126
134
  - `target="_blank"`
127
- - [Rendre les balises accessibles](https://www.w3.org/TR/wai-aria-1.2/#intro_ria_accessibility)
135
+ - [Make the tags accessible](https://www.w3.org/TR/wai-aria-1.2/#intro_ria_accessibility)
128
136
  - [`aria-*`](https://w3c.github.io/using-aria/#aria-states-and-properties-aria-attributes)
129
137
  - [`role`](https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute)
130
138
 
131
- ### Le focus
139
+ ### Focus
132
140
 
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.
141
+ > ⚠️ It's important that the focus in an HTML page is under control. If the focus is lost, the
142
+ > screen reader is lost too.
135
143
  >
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.
144
+ > If, for example, a modal is opened by clicking on a button, then when the modal is closed, the
145
+ > focus must be put back on the triggering button.
138
146
 
139
- Exemple :
147
+ Example:
140
148
 
141
149
  ```html
142
150
  <button
@@ -145,120 +153,129 @@ Exemple :
145
153
  (click)="openModal()"
146
154
  #modalTrigger
147
155
  >
148
- <!-- on déclare le déclencheur de la modale -->
156
+ <!-- we declare the trigger of the modal -->
149
157
  Open Modal
150
158
  </button>
151
159
  <foehn-modal
152
160
  modalHeaderText="Modal dialog"
153
161
  modalSize="modal-lg"
154
- [isModalVisible]="isModalVisible"
155
- (isModalVisibleChange)="updateVisibilityStatus($event)"
162
+ [(isModalVisible)]="isModalVisible"
156
163
  [modalTriggerHtmlElement]="modalTrigger"
157
164
  >
158
- <!-- on utilise le déclencheur -->
165
+ <!-- we use the trigger -->
159
166
  <div>Here is the dialog</div>
160
167
  </foehn-modal>
161
168
  ```
162
169
 
163
- ### La balise `<label>`
170
+ ```ts
171
+ // A signal: the modal is also displayed and hidden without zone.js
172
+ readonly isModalVisible = signal(false);
173
+
174
+ openModal(): void {
175
+ this.isModalVisible.set(true);
176
+ }
177
+ ```
164
178
 
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.
179
+ ### The `<label>` tag
180
+
181
+ > ⚠️ All our `foehn-input-*` components have a label tag ([`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label))
182
+ > which describes the input field. It's important that it is filled with an explicit content.
167
183
  >
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.
184
+ > If for any reason the business doesn't want to display it, you must still fill it and add an
185
+ > `[isLabelSrOnly]="true"` attribute. The label won't be displayed, only read by the screen
186
+ > reader.
171
187
 
172
- Exemple :
188
+ Example:
173
189
 
174
190
  ```html
175
191
  <foehn-input-number
176
192
  name="..."
177
193
  [(model)]="..."
178
- [label]="'Le texte que la liseuse va lire'"
194
+ [label]="'The text read by the screen reader'"
179
195
  [isLabelSrOnly]="true"
180
196
  [required]="..."
181
197
  [maxlength]="..."
182
198
  />
183
199
  ```
184
200
 
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()`, ...
201
+ > 💡 `label`, `isLabelSrOnly`, `required`, ... are now **input signals** in the component.
202
+ > You keep feeding them from the parent template with a `[label]="..."` binding.
203
+ > Inside the component, you read them by calling them: `label()`, `required()`, ...
188
204
 
189
- ### La balise `<ul>` ou `<ol>`
205
+ ### The `<ul>` or `<ol>` tag
190
206
 
191
207
  > ⚠️
192
208
  >
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
209
+ > - The [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) element must be used
210
+ > to group several items that have no order relationship. If you hesitate between
211
+ > [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) and
212
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul), ask yourself whether
213
+ > changing the order of the items of the list has an impact: if moving an item changes the
214
+ > meaning, the order is important and
215
+ > [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) must be used, otherwise
216
+ > the order doesn't matter and [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul)
217
+ > can be used.
218
+ > - If [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) or
219
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) only contains a single
220
+ > [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li) element (not dynamic),
221
+ > ask yourself whether a list is necessary and whether a paragraph
222
+ > ([`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p)) wouldn't be a better
206
223
  > 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).
224
+ > - **NEVER** put a tag other than [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li)
225
+ > between two [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) or
226
+ > [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) tags.
210
227
 
211
- Exemple :
228
+ Example:
212
229
 
213
230
  ```html
214
231
  <ul>
215
- <li>un artichaut</li>
232
+ <li>an artichoke</li>
216
233
  <li>
217
- Les trucs pour le gâteau
218
- <!-- On voit que </li> n'est pas là -->
234
+ The things for the cake
235
+ <!-- Note that </li> isn't there -->
219
236
  <ul>
220
- <li>trois œufs</li>
237
+ <li>three eggs</li>
221
238
  <li>
222
- La génoise
223
- <!-- Là on ouvre une autre liste -->
239
+ The sponge cake
240
+ <!-- Here we open another list -->
224
241
  <ul>
225
- <li>100g de sucre</li>
226
- <li>un œuf</li>
227
- <li>150g de farine</li>
242
+ <li>100g of sugar</li>
243
+ <li>an egg</li>
244
+ <li>150g of flour</li>
228
245
  </ul>
229
246
  </li>
230
- <!-- On ferme la liste la plus imbriquée -->
231
- <li>200g de chocolat</li>
247
+ <!-- We close the most nested list -->
248
+ <li>200g of chocolate</li>
232
249
  </ul>
233
- <!-- On ferme la liste imbriquée avec </li> -->
250
+ <!-- We close the nested list with </li> -->
234
251
  </li>
235
- <li>De l'essuie-tout</li>
252
+ <li>Paper towels</li>
236
253
  <li>
237
- A faire dans l'ordre pour une belle vaisselle
254
+ To do in this order for a nice dishwashing
238
255
  <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>
256
+ <li>Fill the dishwasher</li>
257
+ <li>Put a dishwasher tablet</li>
258
+ <li>Close the door of the dishwasher</li>
259
+ <li>Start the dishwasher</li>
243
260
  </ol>
244
261
  </li>
245
262
  </ul>
246
263
  ```
247
264
 
248
- ### La balise `<fieldset>` et `<legend>`
265
+ ### The `<fieldset>` and `<legend>` tags
249
266
 
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.
267
+ > ⚠️ The HTML element [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) is
268
+ > used to group several interactive controls as well as labels
269
+ > ([`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label)) in an HTML form,
270
+ > and it must have a caption
271
+ > ([`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend)) describing this group.
255
272
  >
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.
273
+ > The HTML element [`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend) represents
274
+ > a caption for the content of its parent element
275
+ > [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset). It can't be
276
+ > used on its own.
260
277
 
261
- Exemple :
278
+ Example:
262
279
 
263
280
  ```html
264
281
  <form>
@@ -277,45 +294,45 @@ Exemple :
277
294
  </form>
278
295
  ```
279
296
 
280
- ### Liseuse d'écran (afficher / masquer)
297
+ ### Screen reader (show / hide)
281
298
 
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.
299
+ > ⚠️ It's important to keep in mind that a screen reader goes through our HTML code. So we can
300
+ > decide at any time to explicitly show it content to read, or to hide content from it so as not to
301
+ > overload the information.
285
302
 
286
- - Afficher uniquement pour la liseuse : utiliser la classe CSS `sr-only`
287
- - Masquer du contenu à la liseuse : utiliser l'attribut `aria-hidden="true"`
303
+ - Show only to the screen reader: use the CSS class `sr-only`
304
+ - Hide content from the screen reader: use the attribute `aria-hidden="true"`
288
305
 
289
- Exemple :
306
+ Example:
290
307
 
291
308
  ```html
292
309
  <a href="https://www.vd.ch">
293
310
  <span class="sr-only">
294
- <!-- Afficher uniquement pour la liseuse d'écran -->
295
- Retour à la page d'accueil
311
+ <!-- Show only to the screen reader -->
312
+ Back to the home page
296
313
  </span>
297
314
  <img
298
315
  aria-hidden="true"
299
316
  class="img-fluid footer-logo"
300
- src="[url_vers_mon_image]"
317
+ src="[url_to_my_image]"
301
318
  alt="Canton de Vaud"
302
319
  />
303
- <!-- Masquer uniquement pour la liseuse d'écran -->
320
+ <!-- Hide only from the screen reader -->
304
321
  </a>
305
322
  ```
306
323
 
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.
324
+ The result of the example above is a link represented by an image for sighted people, and a link
325
+ with text for visually impaired people.
309
326
 
310
- ### Une page prestations-ng
327
+ ### A prestations-ng page
311
328
 
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>`
329
+ 1. Extend the abstract class `AbstractPageComponent`, specifying a model
330
+ 2. Add an h1 title with `setPageTitle`
331
+ 3. Implement the `newForm` function
332
+ 4. Add the `<foehn-form>` in the page (⚠️ **it must not be conditional**)
333
+ 5. The first heading tag of your page must be an h2 (`<h2>`)
334
+ 6. Add `<foehn-navigation>`
335
+ 7. If you have several pages, use the `<foehn-page-counter>` component
319
336
 
320
337
  `page-one.component.ts`
321
338
 
@@ -323,12 +340,12 @@ avec du texte pour les non-voyants.
323
340
  @Component({
324
341
  templateUrl: './page-one.component.html',
325
342
  imports: [
326
- // chaque composant importe ce dont il a besoin dans son template
343
+ // each component imports what its template needs
327
344
  FoehnFormComponent,
328
345
  FoehnNavigationComponent,
329
346
  FoehnPageCounterComponent,
330
347
  SdkDictionaryPipe,
331
- // ... vos composants foehn-* utilisés dans le template
348
+ // ... your foehn-* components used in the template
332
349
  ],
333
350
  })
334
351
  export class PageOneComponent
@@ -337,7 +354,7 @@ export class PageOneComponent
337
354
  {
338
355
  ngOnInit(): void {
339
356
  super.ngOnInit();
340
- // point (2) : ajoutera le titre h1
357
+ // point (2): adds the h1 title
341
358
  this.setPageTitle(this._dictionaryService.getKeySync('page.one.title'));
342
359
  }
343
360
 
@@ -348,28 +365,28 @@ export class PageOneComponent
348
365
  }
349
366
  ```
350
367
 
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.
368
+ > 💡 No more `constructor`: the dependencies of `AbstractPageComponent` (including `_dictionaryService`)
369
+ > are injected with `inject()` in the abstract class. `activatedRoute` is therefore no longer a
370
+ > constructor parameter to pass.
354
371
 
355
372
  `page-one.component.html`
356
373
 
357
374
  ```html
358
375
  <div class="container mt-5">
359
376
  <foehn-page-counter />
360
- <!-- point (7) : si besoin -->
377
+ <!-- point (7): if needed -->
361
378
 
362
- <!-- point (4) : doit toujours être présent dans la page et pas conditionnel (pas de @if) -->
379
+ <!-- point (4): must always be present in the page and not conditional (no @if) -->
363
380
  <foehn-form>
364
381
  <div class="row">
365
382
  <div class="col-md-8">
366
- <!-- point (5) : toujours avoir un <h2> en premier dans votre page -->
383
+ <!-- point (5): always have an <h2> first in your page -->
367
384
  <h2>
368
- {{ 'La_clé_du_dictionnaire_de_votre_titre_H2_ici' |
385
+ {{ 'The_dictionary_key_of_your_H2_title_here' |
369
386
  fromDictionary }}
370
387
  </h2>
371
388
 
372
- <!-- [VOS COMPOSANTS FOEHN ICI] -->
389
+ <!-- [YOUR FOEHN COMPONENTS HERE] -->
373
390
 
374
391
  <foehn-navigation
375
392
  id="navigation"
@@ -383,9 +400,201 @@ export class PageOneComponent
383
400
  </div>
384
401
  ```
385
402
 
386
- ## Le routage de vos pages
403
+ ## Zoneless application
404
+
405
+ > ℹ️ Since v19.2, prestations-ng no longer needs zone.js and we recommend that you make your
406
+ > application zoneless (`provideZonelessChangeDetection()`, see
407
+ > [UPGRADING_V19.md](UPGRADING_V19.md#zoneless-optional-but-recommended)).
408
+ >
409
+ > Without zone.js, Angular only refreshes a component when it is notified of a change:
410
+ >
411
+ > - a listener of its template has been called (`(click)`, `(modelChange)`, `(userInput)`, ...),
412
+ > including the `[(model)]` two-way bindings
413
+ > - a signal read by its template has changed (`signal()`, `computed()`, `input()`, `model()`,
414
+ > `toSignal()`, ...)
415
+ > - `ChangeDetectorRef.markForCheck()` has been called, which is what the `async` pipe does when an
416
+ > observable emits
417
+
418
+ ### Displaying an asynchronous state
419
+
420
+ > ⚠️ A field modified elsewhere (in a `subscribe()`, a `setTimeout()`, a `Promise`, a
421
+ > callback, an `effect()`, ...) is no longer displayed until something else refreshes the component.
422
+ > Hold it in a **signal**.
423
+
424
+ What **not** to do:
425
+
426
+ ```ts
427
+ isLoading = true;
428
+
429
+ ngOnInit(): void {
430
+ this.myService.load().subscribe(() => {
431
+ this.isLoading = false; // not displayed without zone.js
432
+ });
433
+ }
434
+ ```
435
+
436
+ What **to** do:
437
+
438
+ ```ts
439
+ readonly isLoading = signal(true);
440
+
441
+ ngOnInit(): void {
442
+ this.myService.load().subscribe(() => {
443
+ this.isLoading.set(false);
444
+ });
445
+ }
446
+ ```
447
+
448
+ ```html
449
+ @if (isLoading()) {
450
+ <p>{{ 'page.loading' | fromDictionary }}</p>
451
+ }
452
+ ```
453
+
454
+ > 💡 For an observable displayed as is, `toSignal(this.myService.load())` or the `async` pipe do
455
+ > the job for you.
456
+
457
+ Do the same for a field read by the template that only a method called by a listener of the template
458
+ modifies: the listener notifies Angular, but the same method can later be called from a `subscribe()`
459
+ or an `effect()`, and the field would no longer be displayed. A signal notifies Angular whoever
460
+ modifies it.
461
+
462
+ In your pages (`AbstractPageComponent`), `form` can't be a signal. prestations-ng refreshes the page
463
+ when it loads `form` and `reference`, but whenever your code modifies the form, call `markForCheck()`
464
+ after the modifications, whoever calls the method (a listener, a callback, an `effect()`, ...):
465
+
466
+ ```ts
467
+ private readonly changeDetectorRef = inject(ChangeDetectorRef);
468
+
469
+ ngOnInit(): void {
470
+ super.ngOnInit();
471
+ this.sessionInfoWithApplicationService.prefillForm((info) => {
472
+ if (this.form) {
473
+ this.form.firstName = info?.firstName ?? null;
474
+ this.form.lastName = info?.lastName ?? null;
475
+ this.changeDetectorRef.markForCheck();
476
+ }
477
+ });
478
+ }
479
+ ```
480
+
481
+ - Once after the last modification is enough: Angular refreshes the page later, with all the
482
+ modifications of the method. After an `await`, or in another callback, call it again.
483
+ - A signal modified next to the form doesn't replace it: `set()` notifies Angular only when the value
484
+ changes (e.g. an amount recalculated identical), and only refreshes the views reading the signal.
485
+
486
+ If a service fills the form for the page, the page must still be notified: let the service return an
487
+ `Observable` (or take a callback), and call `markForCheck()` in the page.
488
+
489
+ ### Deriving a state from view queries
490
+
491
+ > ⚠️ A field read by the template and modified in `ngAfterViewInit()`, `ngAfterContentInit()` or
492
+ > `ngAfterViewChecked()` is no longer displayed until something else refreshes the component (with
493
+ > zone.js, the next refresh displayed it, after an `NG0100` error in development).
494
+ > Compute it with `computed()` from `viewChild()` or `contentChild()`.
495
+
496
+ What **not** to do:
497
+
498
+ ```ts
499
+ @ViewChild('referenceLink') referenceLink?: TemplateRef<unknown>;
500
+ columns: FoehnTableColumnConfiguration<Order>[] = [];
501
+
502
+ ngAfterViewInit(): void {
503
+ // not displayed without zone.js
504
+ this.columns = [{ id: 'reference', columnLabelKey: 'orders.reference', template: this.referenceLink }];
505
+ }
506
+ ```
507
+
508
+ What **to** do:
509
+
510
+ ```ts
511
+ readonly referenceLink = viewChild<TemplateRef<unknown>>('referenceLink');
512
+ readonly columns = computed<FoehnTableColumnConfiguration<Order>[]>(() => [
513
+ { id: 'reference', columnLabelKey: 'orders.reference', template: this.referenceLink() },
514
+ ]);
515
+ ```
516
+
517
+ ```html
518
+ <foehn-table
519
+ [name]="'orders'"
520
+ [columnsConfiguration]="columns()"
521
+ [model]="orders()"
522
+ ></foehn-table>
523
+
524
+ <ng-template #referenceLink let-order="item">
525
+ <a [routerLink]="['/demande', order.id]">{{ order.reference }}</a>
526
+ </ng-template>
527
+ ```
528
+
529
+ > 💡 The `computed()` follows the result of the `viewChild()`, including when the element appears or
530
+ > disappears in an `@if`: no need to hide the content until it is resolved. If the element must
531
+ > always exist, `viewChild.required()` guarantees it (error `NG0951` otherwise).
532
+
533
+ ### Acting on the DOM after rendering
534
+
535
+ > ⚠️ `NgZone` (`onStable`, `onMicrotaskEmpty`, `run()`, ...) no longer works without zone.js, and a
536
+ > `setTimeout()` doesn't wait for the rendering. To act on the rendered DOM (focus, scroll, ...), use
537
+ > `afterNextRender()`.
538
+
539
+ ```ts
540
+ readonly detailsVisible = signal(false);
541
+ readonly detailsField = viewChild<ElementRef<HTMLElement>>('detailsField');
542
+
543
+ private readonly injector = inject(Injector);
544
+
545
+ showDetails(): void {
546
+ this.detailsVisible.set(true);
547
+ // The field only exists once the details are rendered
548
+ afterNextRender(() => this.detailsField()?.nativeElement.focus(), {
549
+ injector: this.injector,
550
+ });
551
+ }
552
+ ```
553
+
554
+ ### Testing a zoneless component
555
+
556
+ > ⚠️ `fixture.detectChanges()` **forces** the refresh: a component that forgets to notify
557
+ > Angular (a field instead of a signal, a missing `markForCheck()`, ...) passes the test, but isn't
558
+ > refreshed in the application. Let Angular refresh the component, as in production, with
559
+ > `await fixture.whenStable()`.
560
+
561
+ ```ts
562
+ it('should display the details', async () => {
563
+ fixture.componentRef.setInput('showDetails', true);
564
+ await fixture.whenStable();
565
+
566
+ expect(fixture.nativeElement.querySelector('.details')).not.toBeNull();
567
+ });
568
+ ```
569
+
570
+ `await fixture.whenStable()` also waits for the pending tasks of the application, such as the debounced
571
+ `userInput` of the prestations-ng inputs: the test doesn't end before them (otherwise
572
+ `NG0205: Injector has already been destroyed`). But it doesn't wait for the HTTP requests of a spec:
573
+ `provideHttpClientTesting()` keeps them pending until the test answers them. Answer them first with
574
+ `HttpTestingController`, then `await fixture.whenStable()`:
575
+
576
+ ```ts
577
+ it('should display the reference of the demand', async () => {
578
+ httpMock.expectOne('api/demande/1').flush({ reference: 'DEM-1' });
579
+ await fixture.whenStable();
580
+
581
+ expect(fixture.nativeElement.textContent).toContain('DEM-1');
582
+ });
583
+ ```
584
+
585
+ Keep `fixture.detectChanges()` for:
586
+
587
+ - checking an intermediate state, before the end of an asynchronous processing
588
+ - the tests with `vi.useFakeTimers()`: the refresh of Angular goes through timers, which must be
589
+ advanced (`await vi.advanceTimersByTimeAsync(...)`), otherwise `whenStable()` never ends
590
+
591
+ > 💡 So that the test goes through the same path as the user, trigger the events in the
592
+ > DOM (`input.dispatchEvent(new Event('change'))`, `button.click()`, ...) rather than calling the
593
+ > methods of the component or of its services.
387
594
 
388
- ### Formulaire simple
595
+ ## Routing your pages
596
+
597
+ ### Simple form
389
598
 
390
599
  `app.routes.ts`
391
600
 
@@ -425,14 +634,14 @@ export const routes: Routes = [
425
634
  ];
426
635
  ```
427
636
 
428
- ### Formulaire complexe (sous-routes)
637
+ ### Complex form (sub-routes)
429
638
 
430
- > ℹ️ Préférez l'utilisation de **sous-routes** (`*.routes.ts`) pour regrouper vos routes et ainsi
431
- > mieux structurer votre projet.
639
+ > ℹ️ Prefer **sub-routes** (`*.routes.ts`) to group your routes and thus better structure your
640
+ > project.
432
641
  >
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.
642
+ > As there are no more modules (**standalone** components), you no longer load a `*.module.ts` but
643
+ > a routes file exporting a `Routes` constant. See [UPGRADING_V19.md](UPGRADING_V19.md)
644
+ > for the details of the migration.
436
645
 
437
646
  `app.routes.ts`
438
647
 
@@ -472,9 +681,9 @@ export const routes: Routes = [
472
681
  ];
473
682
  ```
474
683
 
475
- > 💡 On charge donc `welcome.routes.ts` (et non plus `welcome.module.ts`) :
684
+ > 💡 So we load `welcome.routes.ts` (and no longer `welcome.module.ts`):
476
685
  > `loadChildren: () => import('./modules/welcome/welcome.routes').then((m) => m.welcome_routes)`
477
- > au lieu de `import('./modules/welcome/welcome.module').then((m) => m.WelcomeModule)`.
686
+ > instead of `import('./modules/welcome/welcome.module').then((m) => m.WelcomeModule)`.
478
687
 
479
688
  `welcome.routes.ts`
480
689
 
@@ -522,47 +731,52 @@ export const inscription_routes: Routes = [
522
731
  ];
523
732
  ```
524
733
 
525
- > 💡 Vous pouvez aussi charger paresseusement (`lazy-load`) un composant :
734
+ > 💡 You can also lazy-load a component:
526
735
  >
527
736
  > ```ts
528
737
  > { path: 'list', loadComponent: () => import('./demande-list-page/demande-list-page.component').then((m) => m.DemandeListPageComponent) },
529
738
  > ```
530
739
 
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 :
740
+ ## Creating a reusable component
741
+
742
+ > ℹ️ Creating a reusable component in Angular isn't difficult, but making it fit prestations-ng is
743
+ > another matter. Some rules must be respected, otherwise it won't work properly.
744
+
745
+ ### Example with foehn-input-date of prestations-ng
746
+
747
+ Your component must:
748
+
749
+ 1. `selector` should start with `"app-..."` to avoid possible naming conflicts
750
+ 2. have a `providers`
751
+ 3. extend `FoehnInputComponent`, to which you must give your data model
752
+ 4. spread the attributes of your data model in public **linked signals** (`linkedSignal()`) used
753
+ in your HTML: they follow the model of your page, and your sub-components change them
754
+ 5. implement an `update` function (here it will be `updateDate`) calling `updateNgModel` to
755
+ keep your data model synchronized with your page
756
+ 6. implement a `handleUserInput` function calling `handleChange` to keep
757
+ notifying the parent of the behavior changes of your component
758
+ 7. not override the `onModelChange` function for your linked signals, which already follow the
759
+ model: override it only to act on a new model of your page (e.g. to normalize it)
760
+ 8. implement a `getValidValue` function to rebuild your data model before sending it
761
+ back to your page, and return `null` if all the attributes of your object are empty (this
762
+ is to keep Java happy), once your model is known (`model_ !== undefined`): it is once the model of
763
+ your page has had a value to display, so that a model without any value (e.g. `[]`) is never
764
+ replaced by `null` without an input of the user
765
+
766
+ > 🚨 **standalone / signals** points to respect:
557
767
  >
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).
768
+ > - **No `multi: true`** in the `providers` (removed since the standalone migration).
769
+ > - The `imports` of the component are declared **directly** in the `@Component` decorator. Each
770
+ > component loads what it needs (see `foehn-input-date` in this project).
771
+ > - The state displayed by the component is held in **linked signals** (point 4), derived from the
772
+ > model: a plain field would not be displayed without zone.js, and a `signal()` filled by
773
+ > `onModelChange` (called by an `effect()`) would follow the model only at the next change
774
+ > detection.
561
775
 
562
776
  `input-date.component.ts`
563
777
 
564
778
  ```ts
565
- import { Component, forwardRef } from '@angular/core';
779
+ import { Component, forwardRef, linkedSignal } from '@angular/core';
566
780
 
567
781
  import { FoehnInputComponent } from '../foehn-input/foehn-input.component';
568
782
  import { FoehnInputNumberComponent } from '../foehn-input/foehn-input-number.component';
@@ -570,7 +784,7 @@ import { FoehnValidationAlertsComponent } from '../foehn-validation-alerts/foehn
570
784
  import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
571
785
 
572
786
  @Component({
573
- // point (1) : dans votre prestation, le selector sera plutôt 'app-...'
787
+ // point (1): in your prestation, the selector will rather be 'app-...'
574
788
  selector: 'app-input-date',
575
789
  templateUrl: './input-date.component.html',
576
790
  // point (2)
@@ -578,10 +792,10 @@ import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
578
792
  {
579
793
  provide: FoehnInputComponent,
580
794
  useExisting: forwardRef(() => InputDateComponent),
581
- // ⚠️ plus de `multi: true` en standalone
795
+ // ⚠️ no more `multi: true` in standalone
582
796
  },
583
797
  ],
584
- // les imports se déclarent directement ici : chaque composant charge ce dont il a besoin
798
+ // the imports are declared directly here: each component loads what it needs
585
799
  imports: [
586
800
  FoehnValidationAlertsComponent,
587
801
  FoehnInputNumberComponent,
@@ -589,12 +803,25 @@ import { SdkDictionaryPipe } from '../sdk-dictionary/sdk-dictionary.pipe';
589
803
  ],
590
804
  })
591
805
  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;
806
+ // point (3): extends FoehnInputComponent<number[]>
807
+
808
+ // point (4): the attributes of your model spread in public linked signals. A new model of your
809
+ // page resets them, a model too short to hold a date keeps them (previous value).
810
+ readonly day = linkedSignal<number[] | null | undefined, string | null>({
811
+ source: this.model,
812
+ computation: (value, previous) =>
813
+ this.getDatePart(value, 2, previous?.value),
814
+ });
815
+ readonly month = linkedSignal<number[] | null | undefined, string | null>({
816
+ source: this.model,
817
+ computation: (value, previous) =>
818
+ this.getDatePart(value, 1, previous?.value),
819
+ });
820
+ readonly year = linkedSignal<number[] | null | undefined, string | null>({
821
+ source: this.model,
822
+ computation: (value, previous) =>
823
+ this.getDatePart(value, 0, previous?.value),
824
+ });
598
825
 
599
826
  // point (5)
600
827
  updateDate(): void {
@@ -612,25 +839,14 @@ export class InputDateComponent extends FoehnInputComponent<number[]> {
612
839
  }
613
840
  }
614
841
 
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
- }
842
+ // point (7): no onModelChange(), the linked signals of point (4) already follow the model
627
843
 
628
844
  // point (8)
629
845
  getValidValue(): number[] | null | undefined {
630
846
  if (
631
- this.isEmpty(this.day) &&
632
- this.isEmpty(this.month) &&
633
- this.isEmpty(this.year)
847
+ this.isEmpty(this.day()) &&
848
+ this.isEmpty(this.month()) &&
849
+ this.isEmpty(this.year())
634
850
  ) {
635
851
  if (this.model_ !== undefined) {
636
852
  return null;
@@ -640,26 +856,43 @@ export class InputDateComponent extends FoehnInputComponent<number[]> {
640
856
  }
641
857
 
642
858
  return [
643
- this.toNumber(this.year),
644
- this.toNumber(this.month),
645
- this.toNumber(this.day),
859
+ this.toNumber(this.year()),
860
+ this.toNumber(this.month()),
861
+ this.toNumber(this.day()),
646
862
  ];
647
863
  }
648
864
 
649
865
  // ...code
866
+
867
+ private getDatePart(
868
+ value: number[] | null | undefined,
869
+ index: number,
870
+ previous: string | null | undefined,
871
+ ): string | null {
872
+ if (value && value.length > 2) {
873
+ return this.toString(value[index]);
874
+ }
875
+ return value ? (previous ?? null) : null;
876
+ }
650
877
  }
651
878
  ```
652
879
 
653
- Chaque `foehn-input-*` utilisé dans votre vue doit :
880
+ > 💡 A field that only reads a property of the model can use the short form, e.g.
881
+ > `readonly street = linkedSignal(() => this.model()?.street ?? null);` (see `foehn-input-address`).
882
+ > It resets the field at every new model: use the form `{ source, computation }`, as above, when a
883
+ > field must keep its value on a partial model.
654
884
 
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)`
885
+ Each `foehn-input-*` used in your view must:
661
886
 
662
- > 💡 `name` est désormais un **input signal**. On l'invoque : `name() + '_day'` (et non plus
887
+ 1. have an `id` concatenating the call to the `buildId()` function and the name of the attribute of your object
888
+ 2. have a `name` concatenating the **signal** input `name()` and the name of the attribute of your object
889
+ 3. have a `label`
890
+ 4. use your public signal as model in two-way binding (banana in the box): `[(model)]="day"`
891
+ reads and writes the signal (without the parentheses)
892
+ 5. call `updateDate()` when the `(modelChange)` event is triggered
893
+ 6. call `handleUserInput()` when the `(userInput)` event is triggered
894
+
895
+ > 💡 `name` is now an **input signal**. You call it: `name() + '_day'` (and no longer
663
896
  > `name + '_day'`).
664
897
 
665
898
  `input-date.component.html`
@@ -702,20 +935,20 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
702
935
  />
703
936
  ```
704
937
 
705
- ### Afficher la validation globale du composant
938
+ ### Displaying the global validation of the component
706
939
 
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.
940
+ - Add the code below in the HTML part of your component
941
+ - Return an error matching the `name` of your component when it is used in
942
+ your form page.
710
943
 
711
- > 💡 Points **signals** à noter dans ce template :
944
+ > 💡 **signals** points to note in this template:
712
945
  >
713
- > - `@if` remplace `*ngIf` et les attributs du composant sont des signaux : on les invoque
946
+ > - `@if` replaces `*ngIf`, and the attributes of the component are signals: you call them
714
947
  > (`label()`, `required()`, `isLabelSrOnly()`, `hideNotRequiredExtraLabel()`, `helpText()`).
715
- > - `[ngClass]` est remplacé par des bindings `[class.xxx]="..."`.
948
+ > - `[ngClass]` is replaced by `[class.xxx]="..."` bindings.
716
949
 
717
950
  ```html
718
- <!-- (obligatoire) Affichera une barre verticale rouge sur l'entier du composant -->
951
+ <!-- (mandatory) Displays a red vertical bar on the whole component -->
719
952
  <div
720
953
  class="form-group"
721
954
  [class.has-danger]="hasErrorsToDisplay()"
@@ -723,12 +956,12 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
723
956
  [attr.id]="buildId('Container')"
724
957
  tabindex="-1"
725
958
  >
726
- <!-- (obligatoire) Permet de regrouper vos champs pour une validation globale -->
959
+ <!-- (mandatory) Groups your fields for a global validation -->
727
960
  <fieldset
728
961
  [attr.aria-describedby]="getDescribedBy()"
729
962
  [attr.aria-invalid]="hasErrorsToDisplay() || null"
730
963
  >
731
- <!-- (facultatif) Seulement si vous souhaitez afficher un label/legend global à votre composant -->
964
+ <!-- (optional) Only if you want to display a global label/legend for your component -->
732
965
  @if (!!label()) {
733
966
  <legend
734
967
  [class.visually-hidden]="isLabelSrOnly()"
@@ -743,10 +976,10 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
743
976
  </legend>
744
977
  }
745
978
 
746
- <!-- (obligatoire) -->
979
+ <!-- (mandatory) -->
747
980
  <foehn-validation-alerts [component]="this" />
748
981
 
749
- <!-- (facultatif) Seulement si vous souhaitez pouvoir afficher un helpText global au composant -->
982
+ <!-- (optional) Only if you want to be able to display a global helpText for the component -->
750
983
  @if (helpText()) {
751
984
  <small
752
985
  [attr.id]="buildId() + 'Help'"
@@ -755,36 +988,36 @@ Chaque `foehn-input-*` utilisé dans votre vue doit :
755
988
  ></small>
756
989
  }
757
990
 
758
- <!-- ...vos foehn-input-* ici -->
991
+ <!-- ...your foehn-input-* here -->
759
992
  </fieldset>
760
993
  </div>
761
994
  ```
762
995
 
763
- ### Éviter des problèmes d'affichage d'erreurs dans une boucle `@for`
996
+ ### Avoiding error display problems in a `@for` loop
764
997
 
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`.
998
+ > ⚠️ Don't forget to put a `track` with a unique identifier in the `@for` loop, otherwise the
999
+ > validation won't be displayed. When a unique identifier such as `id` isn't possible, track
1000
+ > by object or, as a last resort, `track $index`.
768
1001
 
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.
1002
+ > ℹ️ In an Angular `@for` loop with a `FoehnInputComponent` component, if you validate your
1003
+ > form, the errors returned are synchronized with the index of your components repeated in the
1004
+ > loop.
772
1005
  >
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.
1006
+ > **Scenario:** In your list, when you remove a component that has errors at
1007
+ > index 0 (for example) and the next component (index 1) has no errors or not the same
1008
+ > errors, then the latter ends up with the errors of the component just removed at
1009
+ > index 0.
777
1010
  >
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.
1011
+ > **Explanation:** This happens because the errors returned by GESDEM are only
1012
+ > refreshed when the data is saved. So the component removed at
1013
+ > index 0 is replaced by the one at index 1, but the errors at index 0 still exist
1014
+ > and are therefore carried over to the component coming from index 1.
782
1015
 
783
- Voici la bonne pratique à mettre en place pour palier à ces problèmes d'affichage d'erreurs dans une
784
- boucle `@for`.
1016
+ Here is the good practice to put in place to work around these error display problems in a
1017
+ `@for` loop.
785
1018
 
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 :
1019
+ When you remove an item from your list, you must call a method of
1020
+ your `AbstractPageComponent`. This method will contain the following code:
788
1021
 
789
1022
  ```ts
790
1023
  /*
@@ -794,30 +1027,30 @@ votre `AbstractPageComponent`. Cette méthode contiendra le code suivant :
794
1027
  this._gesdemService.validate(this.form).pipe(first()).subscribe();
795
1028
  ```
796
1029
 
797
- Voici un exemple de page de formulaire contenant cette méthode (1) :
1030
+ Here is an example of a form page containing this method (1):
798
1031
 
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()`.
1032
+ > 💡 No more `constructor`: we use **inject**. The dependencies of `AbstractPageComponent`
1033
+ > (including `_dictionaryService` and `_gesdemService`) are already injected in the abstract class. For
1034
+ > your own dependencies, use `inject()`.
802
1035
 
803
1036
  ```ts
804
1037
  @Component({
805
- templateUrl: './votre-page.component.html',
1038
+ templateUrl: './your-page.component.html',
806
1039
  imports: [
807
- // ... vos composants foehn-*
1040
+ // ... your foehn-* components
808
1041
  ],
809
1042
  })
810
- export class VotrePageComponent
1043
+ export class YourPageComponent
811
1044
  extends AbstractPageComponent<BusinessForm>
812
1045
  implements OnInit
813
1046
  {
814
- // vos propres dépendances : inject() au lieu du constructor
1047
+ // your own dependencies: inject() instead of the constructor
815
1048
  private readonly metaService = inject(MetaService);
816
1049
 
817
1050
  ngOnInit(): void {
818
1051
  super.ngOnInit();
819
1052
  this.setPageTitle(
820
- this._dictionaryService.getKeySync('votre-page.title'),
1053
+ this._dictionaryService.getKeySync('your-page.title'),
821
1054
  );
822
1055
  }
823
1056
 
@@ -836,12 +1069,12 @@ export class VotrePageComponent
836
1069
  }
837
1070
  ```
838
1071
 
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.
1072
+ It's up to you to decide how to call this method when the item is removed from
1073
+ your list.
841
1074
 
842
- Voici une manière élégante de gérer vos listes d'éléments :
1075
+ Here is an elegant way to handle your lists of items:
843
1076
 
844
- - Structure des dossiers et fichiers
1077
+ - Structure of the folders and files
845
1078
 
846
1079
  ```text
847
1080
  demande-page/
@@ -858,7 +1091,7 @@ demande-page/
858
1091
 
859
1092
  **vehicule-item**
860
1093
 
861
- `vehicule-item.component.html` contient le bouton pour la suppression de l'élément dans la liste (1).
1094
+ `vehicule-item.component.html` contains the button removing the item from the list (1).
862
1095
 
863
1096
  ```html
864
1097
  <div
@@ -871,7 +1104,7 @@ demande-page/
871
1104
  <foehn-validation-alerts [component]="this" />
872
1105
 
873
1106
  <div class="row d-flex align-items-end vehicule-infos">
874
- <!-- ... vos composants foehn-input-* -->
1107
+ <!-- ... your foehn-input-* components -->
875
1108
 
876
1109
  <div class="col-md-2 mt-md-0 mt-xs-2">
877
1110
  <button class="btn btn-danger" (click)="removeVehicule()">
@@ -883,10 +1116,10 @@ demande-page/
883
1116
  </div>
884
1117
  ```
885
1118
 
886
- `vehicule-item.component.ts` contient la fonction de suppression qui va remonter l'événement à son
887
- parent (la liste des éléments).
1119
+ `vehicule-item.component.ts` contains the removal function, which sends the event up to its
1120
+ parent (the list of items).
888
1121
 
889
- > 💡 `@Output() + EventEmitter` sont remplacés par la fonction `output()`.
1122
+ > 💡 `@Output() + EventEmitter` are replaced by the `output()` function.
890
1123
 
891
1124
  ```ts
892
1125
  @Component({
@@ -900,7 +1133,7 @@ parent (la liste des éléments).
900
1133
  ],
901
1134
  imports: [
902
1135
  FoehnValidationAlertsComponent,
903
- // ... vos foehn-input-*
1136
+ // ... your foehn-input-*
904
1137
  SdkDictionaryPipe,
905
1138
  ],
906
1139
  })
@@ -917,11 +1150,11 @@ export class VehiculeItemComponent extends FoehnInputComponent<Vehicule> {
917
1150
 
918
1151
  **vehicules-list**
919
1152
 
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.
1153
+ `vehicules-list.component.html` contains your `@for` loop (1) and your repeatable component (2), which
1154
+ must also send the event up.
922
1155
 
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`.
1156
+ > ⚠️ In the `@for` loop, don't forget to put a `track` (unique identifier), otherwise the
1157
+ > validation won't be displayed. Here, for example, we track with `vehicule.id`.
925
1158
 
926
1159
  ```html
927
1160
  <div
@@ -954,12 +1187,12 @@ devra lui aussi remonter l'événement.
954
1187
  ></small>
955
1188
  }
956
1189
 
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 -->
1190
+ <!-- (1) your @for loop + track (unique identifier) -->
1191
+ @for (vehicule of vehicules(); track vehicule.id; let i = $index) {
1192
+ <!-- (2) your reusable component -->
960
1193
  <app-vehicule-item
961
1194
  [name]="name() + '[' + i + ']'"
962
- [(model)]="vehicule"
1195
+ [model]="vehicule"
963
1196
  (modelChange)="updateVehiculesList($event, i)"
964
1197
  (userInput)="handleUserInput($event, i)"
965
1198
  (removedVehicule)="handleRemovedVehicule(i)"
@@ -972,12 +1205,15 @@ devra lui aussi remonter l'événement.
972
1205
  </div>
973
1206
  ```
974
1207
 
975
- > 💡 Le `name` est un input signal : `[name]="name() + '[' + i + ']'"` (et non plus
1208
+ > 💡 The `name` is an input signal: `[name]="name() + '[' + i + ']'"` (and no longer
976
1209
  > `[name]="name + '[' + i + ']'"`).
1210
+ >
1211
+ > 💡 The variable of a `@for` loop can't be modified: the item is passed with `[model]`, and
1212
+ > the item of the list is replaced in `updateVehiculesList()` (called by `(modelChange)`).
977
1213
 
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).
1214
+ `vehicules-list.component.ts` in turn sends the event (1) up to the parent (`AbstractPageComponent`)
1215
+ and removes the item from the list (2). This is also where you can handle the addition of an
1216
+ item (3).
981
1217
 
982
1218
  ```ts
983
1219
  @Component({
@@ -996,31 +1232,41 @@ ainsi que supprimer l'élément de la liste (2). C'est aussi ici que vous pouvez
996
1232
  ],
997
1233
  })
998
1234
  export class VehiculesListComponent extends FoehnInputComponent<Vehicule[]> {
999
- readonly removedVehicule = output<void>(); // (1) événement à remonter au parent
1235
+ readonly removedVehicule = output<void>(); // (1) event to send up to the parent
1236
+
1237
+ // Signal holding your repeatable items, derived from the model: it is replaced, never modified in place
1238
+ readonly vehicules = linkedSignal(() => this.model() ?? []);
1000
1239
 
1001
- vehicules: Vehicule[] = []; // Tableau contenant vos éléments répétables
1240
+ updateVehiculesList(vehicule: Vehicule, index: number): void {
1241
+ this.vehicules.update((vehicules) =>
1242
+ vehicules.map((item, i) => (i === index ? vehicule : item)),
1243
+ );
1244
+ this.getValidValueAndUpdateNgModel(); // Update of your model
1245
+ }
1002
1246
 
1003
1247
  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
1248
+ // (2) your function removing the item and sending the event
1249
+ this.vehicules.update((vehicules) =>
1250
+ vehicules.filter((_vehicule, i) => i !== index),
1251
+ ); // removal of the item
1252
+ this.getValidValueAndUpdateNgModel(); // Update of your model
1253
+ this.removedVehicule.emit(); // (1) the event is sent up
1008
1254
  }
1009
1255
 
1010
1256
  addVehicule(): void {
1011
- // (3) Gestion de l'ajout d'un élément
1257
+ // (3) Handling of the addition of an item
1012
1258
  // ...code
1013
1259
  }
1014
1260
  }
1015
1261
  ```
1016
1262
 
1017
- > 💡 Plus besoin de définir une `trackByFn` dédiée : la nouvelle syntaxe `@for` utilise directement
1018
- > l'expression `track` (ici `vehicule.id`).
1263
+ > 💡 No need to define a dedicated `trackByFn` anymore: the new `@for` syntax directly uses
1264
+ > the `track` expression (here `vehicule.id`).
1019
1265
 
1020
1266
  **demande-page**
1021
1267
 
1022
- `demande-page.component.html` utilisera votre composant de liste de véhicule (1) et écoutera pour
1023
- l'événement de suppression (2).
1268
+ `demande-page.component.html` uses your vehicle list component (1) and listens to
1269
+ the removal event (2).
1024
1270
 
1025
1271
  ```html
1026
1272
  <foehn-form>
@@ -1034,7 +1280,7 @@ l'événement de suppression (2).
1034
1280
  [required]="true"
1035
1281
  (removedVehicule)="handleRemovedVehicule()"
1036
1282
  />
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 -->
1283
+ <!-- (1) Use of your list - (2) Call of the method saving the data in GESDEM to refresh the errors -->
1038
1284
 
1039
1285
  <foehn-navigation
1040
1286
  id="navigation"
@@ -1044,8 +1290,8 @@ l'événement de suppression (2).
1044
1290
  </foehn-form>
1045
1291
  ```
1046
1292
 
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.
1293
+ `demande-page.component.ts` calls GESDEM to generate the errors of the
1294
+ form again, and thus refresh the index.
1049
1295
 
1050
1296
  ```ts
1051
1297
  @Component({
@@ -1067,20 +1313,73 @@ export class DemandePageComponent
1067
1313
  }
1068
1314
  ```
1069
1315
 
1070
- ## Validation du formulaire
1316
+ ## Types of the form fields
1317
+
1318
+ > ℹ️ `AbstractPageComponent` replaces `form` with the JSON sent by the backend, as is: at runtime, a field has
1319
+ > the type of the JSON written from the Java model, whatever its TypeScript type says.
1320
+
1321
+ Give the Java field the type matching the model of the component:
1322
+
1323
+ | Component | TypeScript model | Java field |
1324
+ | ------------------------------------------------------------------ | -------------------- | -------------------------------------- |
1325
+ | `foehn-input-text`, `foehn-input-textarea`, `foehn-input-email`... | `string` | `String` |
1326
+ | `foehn-input-time` | `string` | `String` with `@ValidStringTime` |
1327
+ | `foehn-input-date` | `(number \| null)[]` | `LenientLocalDate` |
1328
+ | `foehn-input-date-time` | `(number \| null)[]` | `LenientLocalDateTime` |
1329
+ | `foehn-boolean-checkbox`, `foehn-boolean-radio` | `boolean` | `Boolean` |
1330
+ | `foehn-input-number` | `string` | `Integer`, `BigDecimal`... (see below) |
1331
+
1332
+ > ⚠️ The model of `foehn-input-number` is a `string`: the component keeps the input as typed (decimal comma,
1333
+ > leading zeros, number of decimals). But the Java field is a number (`Integer`, `BigDecimal`), which is
1334
+ > written as a number in the JSON. The field holds `'0'` after the input of the user, and `0` once the form
1335
+ > comes back from the backend. The same happens with any component whose model is a `string` bound to a Java
1336
+ > field which isn't a `String`.
1337
+
1338
+ Never test such a field by its truthiness (`!!value`, `if (value)`, `value || ...`): `'0'` is true, `0` is
1339
+ false.
1340
+
1341
+ What **not** to do:
1342
+
1343
+ ```ts
1344
+ isAmountFilled(): boolean {
1345
+ // true after the input of '0', false once the form is loaded (0)
1346
+ return !!this.form?.amount;
1347
+ }
1348
+ ```
1349
+
1350
+ What **to** do:
1351
+
1352
+ ```ts
1353
+ isAmountFilled(): boolean {
1354
+ const amount = this.form?.amount;
1355
+ return amount !== null && amount !== undefined && amount !== '';
1356
+ }
1357
+
1358
+ getTotal(): number {
1359
+ // Number() converts '12.50' as well as 12.5
1360
+ return Number(this.form?.amount ?? 0) + Number(this.form?.fees ?? 0);
1361
+ }
1362
+ ```
1363
+
1364
+ > ⚠️ The values of the elements of `foehn-select` and `foehn-checkbox` must have the type of the Java field:
1365
+ > they are compared to the model with `===`. With `'1'` as value of an element and `1` sent by the backend
1366
+ > (`Integer`), no element is selected anymore once the form is loaded, and the component warns that the saved
1367
+ > value no longer exists in the list.
1368
+
1369
+ ## Form validation
1071
1370
 
1072
- > ℹ️ Lors de la sauvegarde de votre formulaire dans GESDEM, l'`AbstractPageComponent` gère pour vous
1073
- > l'affichage éventuel des erreurs.
1371
+ > ℹ️ When your form is saved in GESDEM, the `AbstractPageComponent` handles the
1372
+ > display of the errors for you.
1074
1373
  >
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.
1374
+ > If, however, you want to save the data somewhere else than in GESDEM, you will have to handle
1375
+ > the display of the errors manually.
1077
1376
 
1078
- ### Gestion standard
1377
+ ### Standard handling
1079
1378
 
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.
1379
+ > ℹ️ When your data is saved in GESDEM, the display of the errors is handled automatically
1380
+ > for you. However, you must respect some rules.
1082
1381
 
1083
- Prenons un exemple de modèle simple côté front à deux niveaux de profondeur :
1382
+ Let's take an example of a simple front-end model with two levels of depth:
1084
1383
 
1085
1384
  `identification.ts`
1086
1385
 
@@ -1100,8 +1399,8 @@ export class BusinessForm {
1100
1399
  }
1101
1400
  ```
1102
1401
 
1103
- > ⚠️ Le modèle ci-dessus devra impérativement être reflété dans le `name` de vos composants
1104
- > `foehn-input-*` de votre page.
1402
+ > ⚠️ The model above must be reflected in the `name` of the `foehn-input-*`
1403
+ > components of your page.
1105
1404
 
1106
1405
  `page-1.html`
1107
1406
 
@@ -1110,7 +1409,7 @@ export class BusinessForm {
1110
1409
  [(model)]="form.identification.firstName"
1111
1410
  name="identification.firstName"
1112
1411
  />
1113
- <!-- 2 niveaux de profondeur -->
1412
+ <!-- 2 levels of depth -->
1114
1413
 
1115
1414
  <foehn-input-text
1116
1415
  [(model)]="form.identification.lastName"
@@ -1118,26 +1417,26 @@ export class BusinessForm {
1118
1417
  />
1119
1418
 
1120
1419
  <foehn-boolean-checkbox [(model)]="form.acceptCookies" name="acceptCookies" />
1121
- <!-- 1 niveau de profondeur -->
1420
+ <!-- 1 level of depth -->
1122
1421
  ```
1123
1422
 
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 :
1423
+ - On the back-end side, you can handle your errors with the annotations (`@NotEmpty`, `@NotNull`, ...),
1424
+ and **prestations-be** does the rest for you.
1425
+ - If you want to return an error specific to a field of your form, here is the syntax:
1127
1426
 
1128
1427
  ```java
1129
- new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "Le nom est obligatoire si vous ne spécifiez pas de prénom")
1428
+ new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "The last name is required if you don't specify a first name")
1130
1429
  ```
1131
1430
 
1132
- > ⚠️ Le nom de l'erreur doit impérativement correspondre au nom de votre composant dans votre page
1133
- > HTML.
1431
+ > ⚠️ The name of the error must match the name of your component in your HTML
1432
+ > page.
1134
1433
 
1135
- ### Gestion manuelle
1434
+ ### Manual handling
1136
1435
 
1137
1436
  #### Back-end
1138
1437
 
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.
1438
+ On the JAVA back-end side, the server must return an object containing the errors of the form to
1439
+ be compatible with prestations-ng.
1141
1440
 
1142
1441
  ```java
1143
1442
  @Getter
@@ -1151,23 +1450,23 @@ public class PostResponse<T> {
1151
1450
 
1152
1451
  @Builder.Default
1153
1452
  private List<AbstractSdkController.FormError> errors = new ArrayList<>();
1154
- // AbstractSdkController.FormError vient de prestations-be qui est la partie backend de prestations-ng
1453
+ // AbstractSdkController.FormError comes from prestations-be, the backend part of prestations-ng
1155
1454
  }
1156
1455
  ```
1157
1456
 
1158
- Ensuite, ajoutez vos erreurs dans votre modèle avant de le retourner au front-end :
1457
+ Then, add your errors to your model before returning it to the front-end:
1159
1458
 
1160
1459
  ```java
1161
1460
  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"));
1461
+ errors.add(new AbstractSdkController.FormError("identification.lastName", "ErrorCodeHere", "The last name is required if you don't specify a first name"));
1163
1462
 
1164
1463
  PostResponse.<MyObject>builder().dto(myObject).errors(errors).build();
1165
1464
  ```
1166
1465
 
1167
1466
  #### Front-end
1168
1467
 
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.
1468
+ On the front-end side, as for the standard validation, the names of the `foehn-input-*` components of your
1469
+ HTML page and the names of your errors must match.
1171
1470
 
1172
1471
  ```html
1173
1472
  <foehn-input-text
@@ -1176,15 +1475,15 @@ page HTML et le nom de vos erreurs devront correspondre.
1176
1475
  />
1177
1476
  ```
1178
1477
 
1179
- > ⚠️ Au retour de la sauvegarde de vos données, vous allez devoir déclencher manuellement la
1180
- > validation.
1478
+ > ⚠️ When your data has been saved, you will have to trigger the validation
1479
+ > manually.
1181
1480
 
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.
1481
+ 1. In your `page.ts`, create a `handleValidationErrors` function to handle the display of the
1482
+ errors.
1483
+ 2. This function is called when the back-end answers.
1185
1484
 
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 :
1485
+ > 💡 **signals** point: no more `@ViewChild('formWithModels')`. To use a component in the
1486
+ > TypeScript, use a `viewChild(...)` **signal**. Then access the instance by calling it:
1188
1487
  > `this.formWithModels()`.
1189
1488
 
1190
1489
  `page.ts`
@@ -1201,39 +1500,41 @@ import {
1201
1500
  // ...
1202
1501
  })
1203
1502
  export class ... extends AbstractPageComponent<YOUR_MODEL> implements OnInit {
1204
- // point (7 des signaux) : un signal viewChild au lieu de @ViewChild
1503
+ // a viewChild signal instead of @ViewChild
1205
1504
  readonly formWithModels = viewChild(FoehnFormComponent);
1206
1505
 
1207
- // vos propres dépendances via inject()
1506
+ // your own dependencies with inject()
1208
1507
  private readonly httpClient = inject(HttpClient);
1209
1508
 
1210
1509
  ngOnInit(): void {
1211
1510
  super.ngOnInit();
1212
- // Activer l'affichage des erreurs
1511
+ // Enable the display of the errors
1213
1512
  this._validationHandlerService.shouldDisplayErrors(true);
1214
1513
  }
1215
1514
 
1216
- // Fonction de sauvegarde
1515
+ // Save function
1217
1516
  save(): void {
1218
- // Activer l'affichage des erreurs
1517
+ // Enable the display of the errors
1219
1518
  this._validationHandlerService.shouldDisplayErrors(true);
1220
- // Appel au back pour faire votre validation
1519
+ // Call to the back-end to do your validation. The callback modifies no field of the page:
1520
+ // the services of prestations-ng (growl, errors) refresh the display themselves, also
1521
+ // without zone.js. A state of the page modified here should be a signal.
1221
1522
  this.httpClient
1222
- .post<PostResponse>('api_url_ici', votre_objet)
1523
+ .post<PostResponse>('api_url_here', your_object)
1223
1524
  .subscribe((response: PostResponse) => {
1224
1525
  if (!response.errors.length) {
1225
- // On prévient l'utilisateur que tout s'est bien passé
1526
+ // Tell the user that everything went well
1226
1527
  this._growlService.addWithType(
1227
1528
  GrowlType.SUCCESS,
1228
- 'Enregistrement effectué avec succès',
1529
+ 'Saved successfully',
1229
1530
  );
1230
1531
  }
1231
- // Gestion des erreurs au retour du back-end
1532
+ // Handling of the errors returned by the back-end
1232
1533
  this.handleValidationErrors(response.errors); // point (2)
1233
1534
  });
1234
1535
  }
1235
1536
 
1236
- // Affichage des erreurs
1537
+ // Display of the errors
1237
1538
  private handleValidationErrors(errors: ErrorTemplate[]): void {
1238
1539
  // point (1)
1239
1540
  const form = this.formWithModels();
@@ -1251,21 +1552,21 @@ export class ... extends AbstractPageComponent<YOUR_MODEL> implements OnInit {
1251
1552
 
1252
1553
  ```html
1253
1554
  <foehn-form>
1254
- <!-- ... vos composants foehn-input-* -->
1555
+ <!-- ... your foehn-input-* components -->
1255
1556
  </foehn-form>
1256
1557
  ```
1257
1558
 
1258
- ## Validation manuelle d'un composant
1559
+ ## Manual validation of a component
1259
1560
 
1260
- ### Cacher une erreur
1561
+ ### Hiding an error
1261
1562
 
1262
- > ✅ Utiliser la fonction `markAsDirty()` permet de simuler une interaction avec le composant.
1563
+ > ✅ The `markAsDirty()` function simulates an interaction with the component.
1263
1564
  >
1264
- > ℹ️ Permet de cacher l'erreur d'un composant foehn-input en erreur.
1565
+ > ℹ️ Hides the error of a foehn-input component in error.
1265
1566
 
1266
- ### Afficher une erreur
1567
+ ### Displaying an error
1267
1568
 
1268
- > ✅ Utiliser la fonction `markAsPristine()` remet le composant dans son état d'origine comme si
1269
- > aucune interaction n'avait été effectuée.
1569
+ > ✅ The `markAsPristine()` function puts the component back in its original state, as if
1570
+ > no interaction had happened.
1270
1571
  >
1271
- > ℹ️ Permet d'afficher l'erreur d'un composant foehn-input en erreur.
1572
+ > ℹ️ Displays the error of a foehn-input component in error.