Created
January 5, 2026 13:09
-
-
Save bastienapp/916562d70d74c3953ee38f9329c716de to your computer and use it in GitHub Desktop.
Angular gestion d'erreur dans le formulaire
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <main class="container"> | |
| <h2>Sign in</h2> | |
| <form (submit)="signIn($event)"> | |
| <label> | |
| Email : | |
| <input [field]="loginForm.username" type="text" placeholder="[email protected]" /> | |
| </label> | |
| @if (loginForm.username().invalid() && loginForm.username().touched()) { | |
| <div class="error"> | |
| @for (error of loginForm.username().errors(); track error.kind) { | |
| <span>error: {{ error.message }}</span> | |
| } | |
| </div> | |
| } | |
| <label> | |
| Password : | |
| <input [field]="loginForm.password" type="password" /> | |
| </label> | |
| @if (loginForm.password().invalid() && loginForm.password().touched()) { | |
| <div class="error"> | |
| @for (error of loginForm.password().errors(); track error.kind) { | |
| <span>error: {{ error.message }}</span> | |
| } | |
| </div> | |
| } | |
| <button type="submit">Sign in</button> | |
| </form> | |
| </main> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core'; | |
| import { form, Field, email, required, minLength } from '@angular/forms/signals'; | |
| import { AuthService } from '../auth.service'; | |
| @Component({ | |
| selector: 'app-login', | |
| imports: [Field], | |
| templateUrl: './login.html', | |
| changeDetection: ChangeDetectionStrategy.OnPush, | |
| }) | |
| export class Login { | |
| authService = inject(AuthService); | |
| loginModel = signal({ | |
| username: '', | |
| password: '', | |
| }); | |
| // TODO pourquoi la validation marche pas ? | |
| loginForm = form(this.loginModel, (props) => { | |
| email(props.username, { message: "Le format de l'email est incorrect " }); | |
| required(props.username); | |
| required(props.password); | |
| minLength(props.password, 12, { message: 'Le mot de passe doit faire au moins 12 caractères' }); | |
| }); | |
| signIn(event: SubmitEvent) { | |
| event.preventDefault(); | |
| if (this.loginForm().valid()) { | |
| const email = this.loginForm.username().value(); | |
| const password = this.loginForm.password().value(); | |
| this.authService.signIn(email, password); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment