From 328cb5e981b7ec363b373c002a14de59865784ea Mon Sep 17 00:00:00 2001 From: Kai Moritz Date: Tue, 9 Sep 2025 18:32:53 +0200 Subject: [PATCH] refactored login component to use reactive forms --- src/app/login/login.component.html | 10 +++++----- src/app/login/login.component.ts | 24 +++++++++++++++--------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/app/login/login.component.html b/src/app/login/login.component.html index ae88858..6ca848a 100644 --- a/src/app/login/login.component.html +++ b/src/app/login/login.component.html @@ -1,15 +1,15 @@ -
+

- +
{{ error }}
-
Welcome, {{ username }}! Your token is {{ token }}
+
Welcome, {{ form.value.username }}! Your token is {{ token }}
diff --git a/src/app/login/login.component.ts b/src/app/login/login.component.ts index 20d2ddb..8de7ea8 100644 --- a/src/app/login/login.component.ts +++ b/src/app/login/login.component.ts @@ -1,6 +1,6 @@ import { Component, inject } from '@angular/core'; -import { NgIf } from '@angular/common'; -import { FormsModule } from "@angular/forms"; +import { CommonModule } from '@angular/common'; +import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms"; import { Store } from '@ngrx/store'; import { login } from '../store/login.actions'; import { selectError, selectIsLoading, selectToken } from '../store/login.selectors'; @@ -8,8 +8,8 @@ import { selectError, selectIsLoading, selectToken } from '../store/login.select @Component({ selector: 'app-login', imports: [ - NgIf, - FormsModule, + CommonModule, + ReactiveFormsModule ], templateUrl: './login.component.html', styleUrl: './login.component.less' @@ -17,12 +17,18 @@ import { selectError, selectIsLoading, selectToken } from '../store/login.select export class LoginComponent { private store = inject(Store); - username : string|null = null; - password : string|null = null; - token : string|null = null; - error : string|null = null; + form: FormGroup; + error: string|null = null; + token: string|null = null; isLoading : boolean = false; + constructor(private fb: FormBuilder) { + this.form = this.fb.group({ + username: ['', Validators.required], + password: ['', Validators.required] + }); + } + ngOnInit() { this.store.select(selectToken).subscribe(token => (this.token = token)); this.store.select(selectError).subscribe(error => (this.error = error)); @@ -30,6 +36,6 @@ export class LoginComponent { } onSubmit() { - this.store.dispatch(login({ username: this.username, password: this.password })); + this.store.dispatch(login({ username: this.form.value.username, password: this.form.value.password })); } } -- 2.39.5