<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chris Putnam on Medium]]></title>
        <description><![CDATA[Stories by Chris Putnam on Medium]]></description>
        <link>https://medium.com/@putnamtechnology?source=rss-8cf4f35bd929------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dxGe9r4rZz1mAq1QaZs1Og.jpeg</url>
            <title>Stories by Chris Putnam on Medium</title>
            <link>https://medium.com/@putnamtechnology?source=rss-8cf4f35bd929------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:45:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@putnamtechnology/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Account Settings Page (Profile & Security)]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-account-settings-page-profile-security-af32417f8ea2?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/af32417f8ea2</guid>
            <category><![CDATA[web-portal]]></category>
            <category><![CDATA[ui-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[user-profile]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 04:28:35 GMT</pubDate>
            <atom:updated>2026-01-18T04:28:35.334Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1xVbFVZY0PHJqg2SMoxyQ.png" /></figure><p><em>Building a modern Account / Settings screen where users can change passwords, request password reset emails, and manage account actions</em></p><h3>Introduction</h3><p>In our recent UI work, we completed the email verification experience and tightened up the onboarding flow. The next natural step is giving authenticated users a <strong>single place to manage their account</strong> — especially security-critical actions like password changes and account deactivation.</p><p>In this post, we’ll implement an <strong>Account Settings</strong> page in Angular that:</p><ul><li>Exposes key account information (name, email, verification status)</li><li>Lets users <strong>change their password</strong> (authenticated)</li><li>Lets users <strong>request a password reset email</strong> (from within the app)</li><li>Lets users <strong>deactivate their account</strong> (authenticated)</li><li>Adds the page into the existing header user menu</li></ul><h3>Why an Account / Settings Page?</h3><p>Account settings pages are “table stakes” for portal applications:</p><ul><li><strong>Security</strong>: Users need to rotate credentials and recover access</li><li><strong>Self-service</strong>: Reduces support requests</li><li><strong>Trust</strong>: Visible controls for account state and verification reinforce legitimacy</li><li><strong>Consistency</strong>: Puts account actions behind the same UI patterns and validation rules</li></ul><h3>Architecture Overview</h3><p>At a high level, the settings page plugs into our existing auth + API client architecture:</p><pre>Header User Menu<br>    ↓<br>/settings (authGuard protected)<br>    ↓<br>Settings component<br>    ├── Account summary (from localStorage user)<br>    ├── Change password (POST /api/auth/change-password)<br>    ├── Request reset email (POST /api/auth/request-password-reset)<br>    └── Deactivate account (POST /api/auth/deactivate-account → logout)</pre><h3>Step 1: Add a Protected Route</h3><p>We add a new route for the settings page and protect it with authGuard:</p><pre>{<br>  path: &#39;settings&#39;,<br>  loadComponent: () =&gt; import(&#39;./features/account/settings/settings&#39;).then(m =&gt; m.Settings),<br>  canActivate: [authGuard],<br>},</pre><p>This ensures only authenticated users can reach /settings.</p><h3>Step 2: Add a Menu Link in the Header</h3><p>Our header already includes a user menu (person icon) with Logout. We add an <strong>Account Settings</strong> menu item:</p><pre>&lt;button mat-menu-item routerLink=&quot;/settings&quot;&gt;<br>  &lt;mat-icon&gt;settings&lt;/mat-icon&gt;<br>  &lt;span&gt;Account Settings&lt;/span&gt;<br>&lt;/button&gt;</pre><p>Now users can discover the page naturally from the top-right menu.</p><h3>Step 3: Build the Settings Page Layout</h3><p>We create a new feature folder:</p><pre>ui/src/app/features/account/settings/<br>  ├── settings.ts<br>  ├── settings.html<br>  └── settings.scss</pre><p>The page is organized into three cards:</p><ol><li><strong>Account</strong>: Name, email, email verified status (and link to verify)</li><li><strong>Security</strong>: Change password + request reset email</li><li><strong>Account Actions</strong>: Deactivate account (danger zone)</li></ol><p>This mirrors real-world portal UX patterns and keeps security actions clearly separated.</p><h3>Step 4: Display Account Info</h3><p>For now, the settings page reads the current user info from the auth service’s local storage data:</p><ul><li>Display name (first + last)</li><li>Email address</li><li>Email verification status</li></ul><p>If the user isn’t verified, we provide a quick CTA to /verify-email?email=....</p><h3>Step 5: Implement Change Password</h3><p>We use reactive forms with clear validation rules:</p><ul><li>currentPassword: required</li><li>newPassword: required + our shared password policy validator</li><li>confirmNewPassword: required + must match newPassword</li></ul><p>We then call the API:</p><pre>this.apiAuthService.apiAuthChangePasswordPost({ currentPassword, newPassword })</pre><h3>Better validation messaging (reusing our password components)</h3><p>Instead of reinventing password UI, we reuse:</p><ul><li>PasswordInputComponent for the new password (rules + visual feedback)</li><li>PasswordFieldComponent for current/confirm password fields</li></ul><p>We also improved the reusable password field’s error messaging so it can work for non-“Password” labels, and added support for a mismatch error.</p><h3>Step 6: Request a Password Reset Email (In-App)</h3><p>Even when logged in, users may prefer a “reset email” flow — especially if they don’t remember their current password.</p><p>We add a simple button that calls:</p><pre>this.apiAuthService.apiAuthRequestPasswordResetPost({ email })</pre><p>The backend is designed to return a generic success response to prevent email enumeration, so our UI shows a safe message:</p><blockquote><em>“If an account exists for this email, a password reset email has been sent.”</em></blockquote><h3>Step 7: Deactivate Account</h3><p>Account deactivation is an authenticated call:</p><pre>this.apiAuthService.apiAuthDeactivateAccountPost()</pre><p>On success, we immediately call authService.logout() to:</p><ul><li>Clear tokens</li><li>Clear stored user info</li><li>Navigate to login</li></ul><h3>Confirmation dialog</h3><p>For now we use a simple window.confirm(...) to protect users from accidental clicks. In a future refinement, we can replace this with an Angular Material dialog for a more polished experience.</p><h3>Step 8: Utility Class Additions (Success + Surface Containers)</h3><p>To keep styling consistent with the rest of the UI, we added missing utility classes used by both signup and settings pages:</p><ul><li>bg-success-container</li><li>text-on-success-container</li><li>text-primary</li><li>bg-surface-container-highest</li></ul><p>These utilities map directly to Angular Material system variables, keeping our theme consistent without introducing custom colors.</p><h3>Step 9: Fixing Angular Material Content Projection Warnings (NG8011)</h3><p>Angular Material buttons have special content projection rules. When using Angular control flow (@if / @else) inside a mat-button, you can trigger warnings like:</p><blockquote><em>“control flow preventing content projection”</em></blockquote><p>The fix is to ensure each control flow block has a <strong>single root node</strong>, e.g.:</p><pre>@else {<br>  &lt;span class=&quot;d-flex align-items-center gap-2&quot;&gt;<br>    &lt;mat-icon&gt;mail&lt;/mat-icon&gt;<br>    &lt;span&gt;Send Password Reset Email&lt;/span&gt;<br>  &lt;/span&gt;<br>}</pre><p>This keeps the icon projected correctly and removes the warning.</p><h3>Conclusion</h3><p>We now have a functional <strong>Account Settings</strong> page that completes a major piece of portal UX:</p><ul><li>✅ Account summary (name/email/verification status)</li><li>✅ Change password (reusing shared password UI + validators)</li><li>✅ Request password reset email</li><li>✅ Deactivate account + logout</li><li>✅ Discoverable navigation via header user menu</li><li>✅ Cleaner styling via utility class additions</li></ul><p>Next, we can expand this page with profile editing, a dedicated password reset UI flow (request + code entry + new password), and more advanced security features like MFA.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, Account Settings, User Profile, Security, Authentication, Angular Material, Reactive Forms, Form Validation, Change Password, Password Reset, User Experience, UX Design, Web Development, UI Development, Portal Development, Account Management, JWT, Error Handling</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af32417f8ea2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Email Verification UI & User Experience]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-email-verification-ui-user-experience-8bd11b5a7612?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd11b5a7612</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 00:25:05 GMT</pubDate>
            <atom:updated>2026-01-05T00:25:05.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVzmalbYqLyhx_Xt65WpUg.png" /></figure><p><em>Building a complete email verification user interface with manual code entry, resend functionality, and seamless user flows</em></p><h3>Introduction</h3><p>In our previous posts, we implemented email verification on the backend with 6-digit codes and integrated email sending. However, users need a way to verify their email addresses through the UI. In this post, we’ll build a comprehensive email verification interface that supports multiple verification methods, handles expired codes gracefully, and provides a smooth user experience from signup through verification to login.</p><h3>Why Email Verification UI Matters</h3><p>A well-designed email verification interface is crucial for user onboarding:</p><ul><li><strong>User Experience</strong>: Provides multiple ways to verify (click link, enter code manually)</li><li><strong>Accessibility</strong>: Works even when email links don’t function properly</li><li><strong>Error Recovery</strong>: Handles expired codes with resend functionality</li><li><strong>Flow Continuity</strong>: Seamlessly guides users from signup → verification → login</li><li><strong>Trust Building</strong>: Clear feedback and guidance builds user confidence</li></ul><h3>Architecture Overview</h3><p>Our email verification UI consists of:</p><pre>User Signs Up<br>    ↓<br>Redirect to /verify-email?email=user@example.com<br>    ↓<br>Verification Page<br>    ├── Auto-verify if code in URL<br>    ├── Manual entry form (email + code)<br>    ├── Resend code button<br>    └── Error handling with recovery options<br>    ↓<br>Email Verified → Redirect to Login</pre><p>The verification page handles three scenarios:</p><ol><li><strong>Automatic verification</strong>: User clicks link in email (code in URL)</li><li><strong>Manual entry</strong>: User enters email and code manually</li><li><strong>Error recovery</strong>: Code expired or invalid → resend new code</li></ol><h3>Step 1: Creating the Verify Email Component</h3><p>We’ll create a new Angular component for email verification:</p><p><strong>features/auth/verify-email/verify-email.ts:</strong></p><pre>import { Component, inject, OnInit, signal } from &#39;@angular/core&#39;;<br>import { ActivatedRoute, Router, RouterLink } from &#39;@angular/router&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { MatButtonModule } from &#39;@angular/material/button&#39;;<br>import { MatCardModule } from &#39;@angular/material/card&#39;;<br>import { MatIconModule } from &#39;@angular/material/icon&#39;;<br>import { MatProgressSpinnerModule } from &#39;@angular/material/progress-spinner&#39;;<br>import { MatFormFieldModule } from &#39;@angular/material/form-field&#39;;<br>import { MatInputModule } from &#39;@angular/material/input&#39;;<br>import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from &#39;@angular/forms&#39;;<br>import { ConfigService } from &#39;../../../core/services/config.service&#39;;<br>import { AuthService as ApiAuthService } from &#39;../../../core/api/api/auth.service&#39;;<br>import { catchError, finalize, of } from &#39;rxjs&#39;;<br>@Component({<br>  selector: &#39;app-verify-email&#39;,<br>  imports: [<br>    MatCardModule,<br>    MatButtonModule,<br>    MatIconModule,<br>    MatProgressSpinnerModule,<br>    MatFormFieldModule,<br>    MatInputModule,<br>    ReactiveFormsModule,<br>    RouterLink,<br>  ],<br>  templateUrl: &#39;./verify-email.html&#39;,<br>  styleUrl: &#39;./verify-email.scss&#39;,<br>})<br>export class VerifyEmail implements OnInit {<br>  isLoading = signal(false);<br>  isVerified = signal(false);<br>  errorMessage = signal&lt;string | null&gt;(null);<br>  successMessage = signal&lt;string | null&gt;(null);<br>  showManualEntry = signal(false);<br>  isResending = signal(false);<br>  verificationForm: FormGroup;<br>  private route = inject(ActivatedRoute);<br>  private router = inject(Router);<br>  private http = inject(HttpClient);<br>  private configService = inject(ConfigService);<br>  private apiAuthService = inject(ApiAuthService);<br>  private fb = inject(FormBuilder);<br>  constructor() {<br>    this.verificationForm = this.fb.group({<br>      email: [&#39;&#39;, [Validators.required, Validators.email]],<br>      code: [&#39;&#39;, [Validators.required, Validators.pattern(/^\d{6}$/)]],<br>    });<br>  }<br>  ngOnInit(): void {<br>    const email = this.route.snapshot.queryParams[&#39;email&#39;];<br>    const code = this.route.snapshot.queryParams[&#39;code&#39;];<br>    if (email &amp;&amp; code) {<br>      // Auto-verify if both are in URL<br>      this.verifyEmail(email, code);<br>    } else {<br>      // Show manual entry form<br>      this.showManualEntry.set(true);<br>      if (email) {<br>        this.verificationForm.patchValue({ email });<br>      }<br>    }<br>  }<br>  verifyEmail(email: string, code: string): void {<br>    this.isLoading.set(true);<br>    this.errorMessage.set(null);<br>    this.successMessage.set(null);<br>    const apiBaseUrl = this.configService.getApiBaseUrl();<br>    const url = `${apiBaseUrl}/api/auth/verify-email?email=${encodeURIComponent(email)}&amp;code=${encodeURIComponent(code)}`;<br>    this.http.get&lt;{ message: string }&gt;(url)<br>      .pipe(<br>        catchError((error) =&gt; {<br>          if (error.status === 404) {<br>            this.errorMessage.set(&#39;Invalid or expired verification code. Please request a new verification email.&#39;);<br>          } else if (error.status === 400) {<br>            this.errorMessage.set(&#39;Invalid verification link. Please check your email and try again.&#39;);<br>          } else {<br>            this.errorMessage.set(&#39;An error occurred while verifying your email. Please try again.&#39;);<br>          }<br>          return of(null);<br>        }),<br>        finalize(() =&gt; {<br>          this.isLoading.set(false);<br>        })<br>      )<br>      .subscribe((response) =&gt; {<br>        if (response) {<br>          this.isVerified.set(true);<br>          // Redirect to login after 2 seconds<br>          setTimeout(() =&gt; {<br>            this.router.navigate([&#39;/login&#39;], {<br>              queryParams: { verified: &#39;true&#39; }<br>            });<br>          }, 2000);<br>        }<br>      });<br>  }<br>  onSubmitManualVerification(): void {<br>    if (this.verificationForm.valid) {<br>      const email = this.verificationForm.get(&#39;email&#39;)?.value;<br>      const code = this.verificationForm.get(&#39;code&#39;)?.value;<br>      this.verifyEmail(email, code);<br>    }<br>  }<br>  resendVerificationCode(): void {<br>    const email = this.verificationForm.get(&#39;email&#39;)?.value || this.route.snapshot.queryParams[&#39;email&#39;];<br>    <br>    if (!email) {<br>      this.errorMessage.set(&#39;Please enter your email address first.&#39;);<br>      return;<br>    }<br>    this.isResending.set(true);<br>    this.errorMessage.set(null);<br>    this.successMessage.set(null);<br>    this.apiAuthService.apiAuthResendVerificationPost({ email })<br>      .pipe(<br>        catchError((error) =&gt; {<br>          if (error.status === 404) {<br>            this.errorMessage.set(&#39;User not found. Please check your email address.&#39;);<br>          } else if (error.status === 400) {<br>            this.errorMessage.set(&#39;Invalid email address. Please check and try again.&#39;);<br>          } else {<br>            this.errorMessage.set(&#39;Failed to resend verification code. Please try again.&#39;);<br>          }<br>          return of(null);<br>        }),<br>        finalize(() =&gt; {<br>          this.isResending.set(false);<br>        })<br>      )<br>      .subscribe((response) =&gt; {<br>        if (response) {<br>          this.successMessage.set(&#39;A new verification code has been sent to your email. Please check your inbox.&#39;);<br>          this.errorMessage.set(null);<br>          // Clear the code field so user can enter the new code<br>          this.verificationForm.patchValue({ code: &#39;&#39; });<br>        }<br>      });<br>  }<br>}</pre><p><strong>Key Features:</strong></p><ul><li>Handles automatic verification from email links</li><li>Provides manual code entry form</li><li>Validates 6-digit codes with regex pattern</li><li>Shows loading states during verification</li><li>Displays clear error and success messages</li><li>Supports resending verification codes</li></ul><h3>Step 2: Building the Verification Form Template</h3><p>The template provides a clean, user-friendly interface:</p><p><strong>features/auth/verify-email/verify-email.html:</strong></p><pre>&lt;div class=&quot;verify-email-container&quot;&gt;<br>  &lt;mat-card class=&quot;verify-email-card&quot;&gt;<br>    &lt;mat-card-content&gt;<br>      @if (isLoading()) {<br>        &lt;div class=&quot;loading-container&quot;&gt;<br>          &lt;mat-spinner diameter=&quot;40&quot;&gt;&lt;/mat-spinner&gt;<br>          &lt;p&gt;Verifying your email address...&lt;/p&gt;<br>        &lt;/div&gt;<br>      } @else if (isVerified()) {<br>        &lt;div class=&quot;success-container&quot;&gt;<br>          &lt;mat-icon class=&quot;success-icon&quot;&gt;check_circle&lt;/mat-icon&gt;<br>          &lt;h2&gt;Email Verified Successfully!&lt;/h2&gt;<br>          &lt;p&gt;Your email address has been verified. You will be redirected to the login page shortly.&lt;/p&gt;<br>        &lt;/div&gt;<br>      } @else if (showManualEntry()) {<br>        &lt;div class=&quot;manual-entry-container&quot;&gt;<br>          &lt;h2&gt;Verify Your Email&lt;/h2&gt;<br>          &lt;p class=&quot;subtitle&quot;&gt;Enter your email address and the verification code you received&lt;/p&gt;<br>          <br>          &lt;form [formGroup]=&quot;verificationForm&quot; (ngSubmit)=&quot;onSubmitManualVerification()&quot; class=&quot;verification-form&quot;&gt;<br>            &lt;mat-form-field appearance=&quot;outline&quot; class=&quot;w-100&quot;&gt;<br>              &lt;mat-label&gt;Email&lt;/mat-label&gt;<br>              &lt;input matInput type=&quot;email&quot; formControlName=&quot;email&quot; placeholder=&quot;Enter your email&quot;&gt;<br>              &lt;mat-icon matPrefix&gt;email&lt;/mat-icon&gt;<br>              @if (verificationForm.get(&#39;email&#39;)?.hasError(&#39;required&#39;) &amp;&amp; verificationForm.get(&#39;email&#39;)?.touched) {<br>                &lt;mat-error&gt;Email is required&lt;/mat-error&gt;<br>              }<br>              @if (verificationForm.get(&#39;email&#39;)?.hasError(&#39;email&#39;) &amp;&amp; verificationForm.get(&#39;email&#39;)?.touched) {<br>                &lt;mat-error&gt;Please enter a valid email&lt;/mat-error&gt;<br>              }<br>            &lt;/mat-form-field&gt;<br>            &lt;mat-form-field appearance=&quot;outline&quot; class=&quot;w-100&quot;&gt;<br>              &lt;mat-label&gt;Verification Code&lt;/mat-label&gt;<br>              &lt;input matInput type=&quot;text&quot; formControlName=&quot;code&quot; placeholder=&quot;Enter 6-digit code&quot; maxlength=&quot;6&quot;&gt;<br>              &lt;mat-icon matPrefix&gt;vpn_key&lt;/mat-icon&gt;<br>              @if (verificationForm.get(&#39;code&#39;)?.hasError(&#39;required&#39;) &amp;&amp; verificationForm.get(&#39;code&#39;)?.touched) {<br>                &lt;mat-error&gt;Verification code is required&lt;/mat-error&gt;<br>              }<br>              @if (verificationForm.get(&#39;code&#39;)?.hasError(&#39;pattern&#39;) &amp;&amp; verificationForm.get(&#39;code&#39;)?.touched) {<br>                &lt;mat-error&gt;Please enter a valid 6-digit code&lt;/mat-error&gt;<br>              }<br>            &lt;/mat-form-field&gt;<br>            @if (errorMessage()) {<br>              &lt;div class=&quot;error-message&quot;&gt;<br>                {{ errorMessage() }}<br>              &lt;/div&gt;<br>            }<br>            @if (successMessage()) {<br>              &lt;div class=&quot;success-message&quot;&gt;<br>                {{ successMessage() }}<br>              &lt;/div&gt;<br>            }<br>            &lt;button mat-raised-button color=&quot;primary&quot; type=&quot;submit&quot; class=&quot;w-100&quot; [disabled]=&quot;verificationForm.invalid || isLoading() || isResending()&quot;&gt;<br>              @if (isLoading()) {<br>                &lt;span class=&quot;d-flex align-items-center justify-content-center gap-2&quot;&gt;<br>                  &lt;mat-spinner diameter=&quot;20&quot;&gt;&lt;/mat-spinner&gt;<br>                  &lt;span&gt;Verifying...&lt;/span&gt;<br>                &lt;/span&gt;<br>              } @else {<br>                Verify Email<br>              }<br>            &lt;/button&gt;<br>            &lt;button mat-stroked-button type=&quot;button&quot; class=&quot;w-100 mt-2&quot; (click)=&quot;resendVerificationCode()&quot; [disabled]=&quot;isResending() || isLoading() || !verificationForm.get(&#39;email&#39;)?.valid&quot;&gt;<br>              @if (isResending()) {<br>                &lt;span class=&quot;d-flex align-items-center justify-content-center gap-2&quot;&gt;<br>                  &lt;mat-spinner diameter=&quot;20&quot;&gt;&lt;/mat-spinner&gt;<br>                  &lt;span&gt;Sending...&lt;/span&gt;<br>                &lt;/span&gt;<br>              } @else {<br>                &lt;span class=&quot;d-flex align-items-center gap-2&quot;&gt;<br>                  &lt;mat-icon&gt;refresh&lt;/mat-icon&gt;<br>                  &lt;span&gt;Resend Verification Code&lt;/span&gt;<br>                &lt;/span&gt;<br>              }<br>            &lt;/button&gt;<br>          &lt;/form&gt;<br>          &lt;div class=&quot;mt-4 text-center&quot;&gt;<br>            &lt;button mat-button routerLink=&quot;/login&quot; class=&quot;text-sm&quot;&gt;<br>              Back to Login<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      } @else if (errorMessage()) {<br>        &lt;div class=&quot;error-container&quot;&gt;<br>          &lt;mat-icon class=&quot;error-icon&quot;&gt;error&lt;/mat-icon&gt;<br>          &lt;h2&gt;Verification Failed&lt;/h2&gt;<br>          &lt;p&gt;{{ errorMessage() }}&lt;/p&gt;<br>          <br>          @if (successMessage()) {<br>            &lt;div class=&quot;success-message mt-3&quot;&gt;<br>              {{ successMessage() }}<br>            &lt;/div&gt;<br>          }<br>          &lt;div class=&quot;mt-4&quot;&gt;<br>            &lt;button mat-raised-button color=&quot;primary&quot; (click)=&quot;showManualEntry.set(true)&quot; class=&quot;mb-2 w-100&quot;&gt;<br>              Enter Code Manually<br>            &lt;/button&gt;<br>            &lt;button mat-stroked-button (click)=&quot;resendVerificationCode()&quot; class=&quot;mb-2 w-100&quot; [disabled]=&quot;isResending()&quot;&gt;<br>              @if (isResending()) {<br>                &lt;span class=&quot;d-flex align-items-center justify-content-center gap-2&quot;&gt;<br>                  &lt;mat-spinner diameter=&quot;20&quot;&gt;&lt;/mat-spinner&gt;<br>                  &lt;span&gt;Sending...&lt;/span&gt;<br>                &lt;/span&gt;<br>              } @else {<br>                &lt;span class=&quot;d-flex align-items-center gap-2&quot;&gt;<br>                  &lt;mat-icon&gt;refresh&lt;/mat-icon&gt;<br>                  &lt;span&gt;Resend Verification Code&lt;/span&gt;<br>                &lt;/span&gt;<br>              }<br>            &lt;/button&gt;<br>            &lt;button mat-button routerLink=&quot;/login&quot; class=&quot;mt-2 w-100&quot;&gt;<br>              Go to Login<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      }<br>    &lt;/mat-card-content&gt;<br>  &lt;/mat-card&gt;<br>&lt;/div&gt;</pre><p><strong>Template Features:</strong></p><ul><li>Loading state with spinner</li><li>Success state with checkmark icon</li><li>Manual entry form with validation</li><li>Error state with recovery options</li><li>Resend button with loading state</li><li>Flexbox-aligned icon and text</li></ul><h3>Step 3: Adding the Route</h3><p>We add the verification route to our routing configuration:</p><p><strong>app.routes.ts:</strong></p><pre>export const routes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    loadComponent: () =&gt; import(&#39;./features/home/home&#39;).then(m =&gt; m.Home),<br>    canActivate: [authGuard],<br>  },<br>  {<br>    path: &#39;login&#39;,<br>    loadComponent: () =&gt; import(&#39;./features/auth/login/login&#39;).then(m =&gt; m.Login),<br>  },<br>  {<br>    path: &#39;signup&#39;,<br>    loadComponent: () =&gt; import(&#39;./features/auth/signup/signup&#39;).then(m =&gt; m.Signup),<br>  },<br>  {<br>    path: &#39;verify-email&#39;,<br>    loadComponent: () =&gt; import(&#39;./features/auth/verify-email/verify-email&#39;).then(m =&gt; m.VerifyEmail),<br>  },<br>  {<br>    path: &#39;**&#39;,<br>    redirectTo: &#39;&#39;,<br>  },<br>];</pre><h3>Step 4: Redirecting from Signup</h3><p>After successful signup, we redirect users directly to the verification page:</p><p><strong>features/auth/signup/signup.ts:</strong></p><pre>switchMap((createUserDto) =&gt;<br>  this.userService.apiUserPost(createUserDto).pipe(<br>    tap((response) =&gt; {<br>      // After successful signup, redirect to verification page<br>      this.successMessage.set(&#39;Account created successfully! Please verify your email.&#39;);<br>      <br>      // Navigate to verify-email page with email pre-filled<br>      setTimeout(() =&gt; {<br>        this.router.navigate([&#39;/verify-email&#39;], {<br>          queryParams: { email: createUserDto.email }<br>        });<br>      }, 1500);<br>    }),<br>    // ... error handling<br>  )<br>)</pre><p><strong>Benefits:</strong></p><ul><li>Users immediately see where to verify their email</li><li>Email is pre-filled in the form</li><li>Clear next step in the onboarding flow</li><li>No confusion about what to do next</li></ul><h3>Step 5: Auto-Redirect from Login for Unverified Users</h3><p>When users try to log in with an unverified email, we automatically redirect them to the verification page:</p><p><strong>features/auth/login/login.ts:</strong></p><pre>catchError((error) =&gt; {<br>  console.error(&#39;Login error:&#39;, error);<br>  // Handle different error types<br>  if (error.status === 401) {<br>    const errorMessage = error.error?.message || error.error?.detail || &#39;Invalid email or password&#39;;<br>    <br>    // Check if the error is about unverified email<br>    const lowerMessage = errorMessage.toLowerCase();<br>    if (lowerMessage.includes(&#39;verify&#39;) &amp;&amp; lowerMessage.includes(&#39;email&#39;)) {<br>      // Redirect to verify-email page with the email pre-filled<br>      const email = this.loginForm.get(&#39;email&#39;)?.value;<br>      if (email) {<br>        this.router.navigate([&#39;/verify-email&#39;], {<br>          queryParams: { email: email }<br>        });<br>        return EMPTY;<br>      }<br>    }<br>    <br>    this.errorMessage.set(errorMessage);<br>  }<br>  // ... other error handling<br>})</pre><p><strong>User Experience:</strong></p><ul><li>Users don’t see a confusing error message</li><li>They’re automatically guided to the verification page</li><li>Email is pre-filled for convenience</li><li>Clear path to complete verification</li></ul><h3>Step 6: Enhancing the Email Template</h3><p>We update the email template to include a manual entry link:</p><p><strong>api/Portal.Api.Services/Services/EmailService.cs:</strong></p><pre>public async Task&lt;bool&gt; SendVerificationEmailAsync(<br>    string toEmail, <br>    string toName, <br>    string verificationCode, <br>    string verificationLink, <br>    CancellationToken cancellationToken = default)<br>{<br>    // Extract base URL from verification link to build manual entry link<br>    var baseUrl = verificationLink.Split(&#39;?&#39;)[0].Replace(&quot;/verify-email&quot;, &quot;&quot;);<br>    var manualEntryLink = $&quot;{baseUrl}/verify-email?email={Uri.EscapeDataString(toEmail)}&quot;;<br>var subject = &quot;Verify Your Email Address&quot;;<br>    var body = $@&quot;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;&quot;utf-8&quot;&quot;&gt;<br>    &lt;style&gt;<br>        /* ... styles ... */<br>        .button-secondary {{<br>            display: inline-block;<br>            background-color: #2196F3;<br>            color: white;<br>            padding: 12px 24px;<br>            text-decoration: none;<br>            border-radius: 5px;<br>            margin: 10px 5px;<br>            font-weight: bold;<br>            font-size: 14px;<br>        }}<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;&quot;container&quot;&quot;&gt;<br>        &lt;div class=&quot;&quot;header&quot;&quot;&gt;<br>            &lt;h1&gt;Verify Your Email Address&lt;/h1&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;&quot;content&quot;&quot;&gt;<br>            &lt;p&gt;Hello {toName},&lt;/p&gt;<br>            &lt;p&gt;Thank you for registering with us! Please verify your email address by clicking the button below:&lt;/p&gt;<br>            &lt;div style=&quot;&quot;text-align: center;&quot;&quot;&gt;<br>                &lt;a href=&quot;&quot;{verificationLink}&quot;&quot; class=&quot;&quot;button&quot;&quot;&gt;Verify Email Address&lt;/a&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;&quot;alternative&quot;&quot;&gt;<br>                &lt;p&gt;&lt;strong&gt;Or copy and paste this link into your browser:&lt;/strong&gt;&lt;/p&gt;<br>                &lt;p style=&quot;&quot;word-break: break-all; color: #4CAF50;&quot;&quot;&gt;{verificationLink}&lt;/p&gt;<br>                &lt;p&gt;&lt;strong&gt;Or enter this verification code manually:&lt;/strong&gt;&lt;/p&gt;<br>                &lt;div class=&quot;&quot;code&quot;&quot;&gt;{verificationCode}&lt;/div&gt;<br>                &lt;div style=&quot;&quot;text-align: center; margin-top: 15px;&quot;&quot;&gt;<br>                    &lt;a href=&quot;&quot;{manualEntryLink}&quot;&quot; class=&quot;&quot;button-secondary&quot;&quot;&gt;Enter Code Manually&lt;/a&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;p&gt;This verification link will expire in 24 hours.&lt;/p&gt;<br>            &lt;p&gt;If you didn&#39;t create an account, please ignore this email.&lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;&quot;;<br>    return await SendEmailAsync(toEmail, toName, subject, body, cancellationToken);<br>}</pre><p><strong>Email Features:</strong></p><ul><li>Primary “Verify Email Address” button (auto-verification)</li><li>Manual entry link for users who prefer to enter code</li><li>Large, easy-to-read 6-digit code display</li><li>Clear expiration notice</li><li>Multiple verification options</li></ul><h3>Step 7: Handling Expired Codes</h3><p>When a verification code expires, users see a helpful error message and can easily request a new one:</p><p><strong>Error Handling:</strong></p><pre>catchError((error) =&gt; {<br>  if (error.status === 404) {<br>    this.errorMessage.set(&#39;Invalid or expired verification code. Please request a new verification email.&#39;);<br>  }<br>  // ... other errors<br>})</pre><p><strong>Resend Functionality:</strong></p><ul><li>Button appears in both manual entry form and error state</li><li>Calls /api/auth/resend-verification endpoint</li><li>Shows success message when new code is sent</li><li>Clears code field so user can enter new code</li><li>Handles errors gracefully (user not found, invalid email, etc.)</li></ul><h3>User Flow Summary</h3><p>The complete user journey:</p><ol><li><strong>Signup</strong>: User creates account → Redirected to /verify-email?email=user@example.com</li><li><strong>Email Received</strong>: User receives email with:</li></ol><ul><li>Click-to-verify button</li><li>Manual entry link</li><li>6-digit code displayed</li></ul><ol><li><strong>Verification Options</strong>:</li></ol><ul><li><strong>Option A</strong>: Click button → Auto-verified → Redirected to login</li><li><strong>Option B</strong>: Click manual entry link → Form with email pre-filled → Enter code → Verified</li><li><strong>Option C</strong>: Navigate directly → Enter email and code manually → Verified</li></ul><ol><li><strong>Error Recovery</strong>: If code expired → Click resend → New code sent → Enter new code → Verified</li><li><strong>Login Attempt</strong>: If user tries to login unverified → Auto-redirected to verification page</li><li><strong>Success</strong>: Email verified → Redirected to login → Can now log in</li></ol><h3>Key Design Decisions</h3><ol><li><strong>Multiple Verification Methods</strong>: Supports both automatic (link) and manual (code entry) verification</li><li><strong>Pre-filled Email</strong>: Reduces friction by pre-filling email from URL or form</li><li><strong>Clear Error Messages</strong>: Specific messages for expired codes, invalid codes, etc.</li><li><strong>Resend Functionality</strong>: Easy recovery path when codes expire</li><li><strong>Auto-redirects</strong>: Seamless flow from signup and login attempts</li><li><strong>Loading States</strong>: Clear feedback during async operations</li><li><strong>Flexbox Alignment</strong>: Proper icon and text alignment in buttons</li></ol><h3>Testing Considerations</h3><p>When testing the verification flow:</p><ol><li><strong>Automatic Verification</strong>: Click email link → Should auto-verify</li><li><strong>Manual Entry</strong>: Enter email and code → Should verify</li><li><strong>Expired Code</strong>: Use old code → Should show error → Resend → Should work</li><li><strong>Invalid Code</strong>: Enter wrong code → Should show error</li><li><strong>Resend</strong>: Click resend → Should receive new code → Should verify with new code</li><li><strong>Signup Flow</strong>: Sign up → Should redirect to verification page</li><li><strong>Login Flow</strong>: Try to login unverified → Should redirect to verification page</li></ol><h3>Conclusion</h3><p>We’ve built a comprehensive email verification UI that provides multiple verification methods, handles errors gracefully, and guides users through a smooth onboarding experience. The implementation includes:</p><ul><li>✅ Automatic verification from email links</li><li>✅ Manual code entry form</li><li>✅ Resend functionality for expired codes</li><li>✅ Auto-redirect from signup</li><li>✅ Auto-redirect from login for unverified users</li><li>✅ Enhanced email template with manual entry link</li><li>✅ Clear error messages and recovery paths</li><li>✅ Loading states and user feedback</li></ul><p>The verification system is now complete and production-ready, providing users with a seamless path from signup to verified account to login.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, Email Verification, User Experience, User Onboarding, Angular Material, Reactive Forms, Form Validation, Component Architecture, Material Design, Authentication, Web Development, UI Development, Error Handling, User Flows, Email Templates, .NET Core, ASP.NET Core, User Interface Design, Form Design, Routing, Navigation, Error Recovery, Resend Functionality</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd11b5a7612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Building a Reusable Password Input Component]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-building-a-reusable-password-input-component-2cacd04f64a0?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cacd04f64a0</guid>
            <category><![CDATA[angular-material]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[form-validation]]></category>
            <category><![CDATA[custom-form-control]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 04:33:31 GMT</pubDate>
            <atom:updated>2026-01-02T04:33:31.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbgUsIkA-BGJQ5m9nTX6hw.png" /></figure><p><em>Creating a reusable password input component with visual validation feedback and confirm password functionality</em></p><h3>Introduction</h3><p>In our previous post, we built the sign up form with comprehensive validation. During that implementation, we discovered that password validation was complex and would be needed in multiple places (sign up, password reset, change password). Instead of duplicating this logic, we created a reusable PasswordInputComponent that provides visual feedback, confirm password validation, and integrates seamlessly with Angular&#39;s reactive forms.</p><h3>Why a Reusable Password Component?</h3><p>Creating a dedicated password input component provides several benefits:</p><ol><li><strong>Reusability</strong>: Use the same component across sign up, password reset, and change password forms</li><li><strong>Consistency</strong>: Uniform password validation and UI across the application</li><li><strong>User Experience</strong>: Visual feedback with checkmarks/X icons for password rules</li><li><strong>Maintainability</strong>: Single source of truth for password validation logic</li><li><strong>Accessibility</strong>: Built-in accessibility features (ARIA labels, keyboard navigation)</li><li><strong>Form Integration</strong>: Seamless integration with Angular reactive forms via ControlValueAccessor</li><li><strong>Customization</strong>: Configurable options (show rules, show confirm password, labels)</li></ol><h3>Architecture Overview</h3><p>Our password input component consists of two components working together:</p><pre>PasswordInputComponent (main component)<br>    ↓<br>    ├── PasswordFieldComponent (reusable single password field)<br>    │       ├── ControlValueAccessor (form integration)<br>    │       ├── Internal FormControl (for Material Design)<br>    │       ├── Error state syncing<br>    │       └── Visibility toggle<br>    │<br>    ├── Password Rules (computed signals)<br>    ├── Visual Feedback (checkmarks/X icons)<br>    └── Confirm Password (optional, uses PasswordFieldComponent)</pre><p>The architecture uses two components:</p><ol><li><strong>PasswordFieldComponent</strong>: A reusable single password input field with visibility toggle and automatic error display</li><li><strong>PasswordInputComponent</strong>: The main component that uses PasswordFieldComponent and adds password rules validation and confirm password functionality</li></ol><h3>Step 1: Building the Reusable Password Field Component</h3><p>First, we’ll create a reusable PasswordFieldComponent that handles a single password input with visibility toggle and automatic error display. This component is used internally by PasswordInputComponent and can also be used standalone (e.g., in the login form).</p><p><strong>shared/components/password-field/password-field.ts:</strong></p><pre>import { Component, forwardRef, input, output, Injector, signal, effect, inject, afterNextRender, ChangeDetectorRef, DestroyRef } from &#39;@angular/core&#39;;<br>import { ControlValueAccessor, NG_VALUE_ACCESSOR, NgControl, ReactiveFormsModule, FormControl } from &#39;@angular/forms&#39;;<br>import { MatFormFieldModule } from &#39;@angular/material/form-field&#39;;<br>import { MatInputModule } from &#39;@angular/material/input&#39;;<br>import { MatIconModule } from &#39;@angular/material/icon&#39;;<br>import { MatButtonModule } from &#39;@angular/material/button&#39;;<br>import { takeUntilDestroyed } from &#39;@angular/core/rxjs-interop&#39;;<br>@Component({<br>  selector: &#39;app-password-field&#39;,<br>  imports: [<br>    ReactiveFormsModule,<br>    MatFormFieldModule,<br>    MatInputModule,<br>    MatIconModule,<br>    MatButtonModule,<br>  ],<br>  templateUrl: &#39;./password-field.html&#39;,<br>  styleUrl: &#39;./password-field.scss&#39;,<br>  providers: [<br>    {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: forwardRef(() =&gt; PasswordFieldComponent),<br>      multi: true,<br>    },<br>  ],<br>})<br>export class PasswordFieldComponent implements ControlValueAccessor {<br>  label = input&lt;string&gt;(&#39;Password&#39;);<br>  placeholder = input&lt;string&gt;(&#39;Enter your password&#39;);<br>  value = input&lt;string&gt;(&#39;&#39;);<br>  valueChange = output&lt;string&gt;();<br>  touched = output&lt;void&gt;();<br>  id = `app-password-field-${nextId++}`;<br>  internalValue = signal&lt;string&gt;(&#39;&#39;);<br>  disabled = signal&lt;boolean&gt;(false);<br>  showPassword = signal&lt;boolean&gt;(false);<br>  private controlInvalid = signal&lt;boolean&gt;(false);<br>  private controlTouched = signal&lt;boolean&gt;(false);<br>  private controlDirty = signal&lt;boolean&gt;(false);<br>  private controlErrors = signal&lt;any&gt;(null);<br>  showError = signal&lt;boolean&gt;(false);<br>  errorMessage = signal&lt;string&gt;(&#39;&#39;);<br>  private injector = inject(Injector);<br>  private cdr = inject(ChangeDetectorRef);<br>  private destroyRef = inject(DestroyRef);<br>  public ngControl: NgControl | null = null;<br>  // Create a FormControl that mirrors the parent control for Material to track<br>  internalFormControl = new FormControl(&#39;&#39;);<br>  constructor() {<br>    afterNextRender(() =&gt; {<br>      try {<br>        this.ngControl = this.injector.get(NgControl, null, { optional: true, self: true });<br>        if (this.ngControl) {<br>          if (this.ngControl.valueAccessor !== this) {<br>            this.ngControl.valueAccessor = this;<br>          }<br>          this.updateControlStateSignals();<br>          if (this.ngControl.control) {<br>            const control = this.ngControl.control;<br>            // Sync parent control state to internal FormControl<br>            this.syncControlState();<br>            control.statusChanges<br>              .pipe(takeUntilDestroyed(this.destroyRef))<br>              .subscribe(() =&gt; {<br>                this.updateControlStateSignals();<br>                this.syncControlState();<br>              });<br>            control.valueChanges<br>              .pipe(takeUntilDestroyed(this.destroyRef))<br>              .subscribe(() =&gt; {<br>                this.updateControlStateSignals();<br>                this.syncControlState();<br>              });<br>          }<br>        }<br>      } catch (e) {<br>        this.ngControl = null;<br>      }<br>    });<br>    effect(() =&gt; {<br>      const inputValue = this.value();<br>      if (!this.ngControl &amp;&amp; inputValue !== undefined &amp;&amp; inputValue !== this.internalValue()) {<br>        this.internalValue.set(inputValue);<br>      }<br>    });<br>  }<br>  get control() {<br>    return this.ngControl?.control;<br>  }<br>  private syncControlState(): void {<br>    const c = this.control;<br>    if (c) {<br>      // Sync errors to internal FormControl so Material can see them<br>      this.internalFormControl.setErrors(c.errors);<br>      // Mark as touched/dirty to match parent<br>      if (c.touched &amp;&amp; !this.internalFormControl.touched) {<br>        this.internalFormControl.markAsTouched();<br>      }<br>      if (c.dirty &amp;&amp; !this.internalFormControl.dirty) {<br>        this.internalFormControl.markAsDirty();<br>      }<br>      this.cdr.markForCheck();<br>    }<br>  }<br>  private updateControlStateSignals(): void {<br>    const c = this.control;<br>    if (c) {<br>      this.controlInvalid.set(c.invalid);<br>      this.controlTouched.set(c.touched);<br>      this.controlDirty.set(c.dirty);<br>      this.controlErrors.set(c.errors);<br>      this.updateErrorDisplay();<br>      this.cdr.markForCheck();<br>    }<br>  }<br>  private updateErrorDisplay(): void {<br>    const invalid = this.controlInvalid();<br>    const touched = this.controlTouched();<br>    const dirty = this.controlDirty();<br>    const errors = this.controlErrors();<br>    const shouldShow = invalid &amp;&amp; (dirty || touched);<br>    let message = &#39;&#39;;<br>    if (shouldShow &amp;&amp; errors) {<br>      if (errors[&#39;required&#39;]) {<br>        message = &#39;Password is required&#39;;<br>      } else if (errors[&#39;minlength&#39;]) {<br>        message = `Password must be at least ${errors[&#39;minlength&#39;].requiredLength} characters`;<br>      } else if (errors[&#39;maxlength&#39;]) {<br>        message = `Password must be no more than ${errors[&#39;maxlength&#39;].requiredLength} characters`;<br>      } else if (errors[&#39;hasUppercase&#39;]) {<br>        message = &#39;Password must contain at least one uppercase letter&#39;;<br>      } else if (errors[&#39;hasLowercase&#39;]) {<br>        message = &#39;Password must contain at least one lowercase letter&#39;;<br>      } else if (errors[&#39;hasDigit&#39;]) {<br>        message = &#39;Password must contain at least one digit&#39;;<br>      } else if (errors[&#39;hasSpecialChar&#39;]) {<br>        message = &#39;Password must contain at least one special character&#39;;<br>      } else {<br>        message = &#39;Invalid password&#39;;<br>      }<br>    }<br>    this.showError.set(shouldShow);<br>    this.errorMessage.set(message);<br>  }<br>  // ControlValueAccessor implementation<br>  private onChange: (val: string) =&gt; void = () =&gt; {};<br>  private onTouched: () =&gt; void = () =&gt; {};<br>  writeValue(val: unknown): void {<br>    this.internalValue.set((val ?? &#39;&#39;) as string);<br>    this.internalFormControl.setValue(val as string, { emitEvent: false });<br>  }<br>  registerOnChange(fn: (val: string) =&gt; void): void {<br>    this.onChange = fn;<br>  }<br>  registerOnTouched(fn: () =&gt; void): void {<br>    this.onTouched = fn;<br>  }<br>  setDisabledState(isDisabled: boolean): void {<br>    this.disabled.set(isDisabled);<br>    if (isDisabled) {<br>      this.internalFormControl.disable({ emitEvent: false });<br>    } else {<br>      this.internalFormControl.enable({ emitEvent: false });<br>    }<br>  }<br>  handleInput(event: Event): void {<br>    const v = (event.target as HTMLInputElement).value;<br>    this.internalValue.set(v);<br>    if (this.ngControl) {<br>      this.onChange(v);<br>      setTimeout(() =&gt; this.updateControlStateSignals(), 0);<br>    } else {<br>      this.valueChange.emit(v);<br>    }<br>  }<br>  handleBlur(): void {<br>    if (this.ngControl) {<br>      this.onTouched();<br>      setTimeout(() =&gt; this.updateControlStateSignals(), 0);<br>    } else {<br>      this.touched.emit();<br>    }<br>  }<br>  togglePasswordVisibility(): void {<br>    this.showPassword.update(v =&gt; !v);<br>  }<br>}</pre><p><strong>shared/components/password-field/password-field.html:</strong></p><pre>&lt;mat-form-field appearance=&quot;outline&quot; class=&quot;w-100&quot;&gt;<br>  &lt;mat-label&gt;{{ label() }}&lt;/mat-label&gt;<br>  &lt;input<br>    matInput<br>    [id]=&quot;id&quot;<br>    [type]=&quot;showPassword() ? &#39;text&#39; : &#39;password&#39;&quot;<br>    [placeholder]=&quot;placeholder()&quot;<br>    [formControl]=&quot;internalFormControl&quot;<br>    [disabled]=&quot;disabled()&quot;<br>    (input)=&quot;handleInput($event)&quot;<br>    (blur)=&quot;handleBlur()&quot;<br>  /&gt;<br>  &lt;mat-icon matPrefix&gt;lock&lt;/mat-icon&gt;<br>  &lt;button<br>    mat-icon-button<br>    matSuffix<br>    type=&quot;button&quot;<br>    (click)=&quot;togglePasswordVisibility()&quot;<br>    [attr.aria-label]=&quot;showPassword() ? &#39;Hide password&#39; : &#39;Show password&#39;&quot;<br>    tabindex=&quot;-1&quot;&gt;<br>    &lt;mat-icon&gt;{{ showPassword() ? &#39;visibility_off&#39; : &#39;visibility&#39; }}&lt;/mat-icon&gt;<br>  &lt;/button&gt;<br>  &lt;ng-content&gt;&lt;/ng-content&gt;<br>  &lt;mat-error&gt;<br>    {{ errorMessage() }}<br>  &lt;/mat-error&gt;<br>&lt;/mat-form-field&gt;</pre><h3>Key Features of PasswordFieldComponent</h3><ol><li><strong>Internal FormControl</strong>: Uses [formControl]=&quot;internalFormControl&quot; so Material Design can track the form control state and display the red border</li><li><strong>State Syncing</strong>: Syncs the parent form control’s errors, touched, and dirty states to the internal FormControl</li><li><strong>Automatic Error Display</strong>: Automatically displays error messages based on form control validation</li><li><strong>ControlValueAccessor</strong>: Implements ControlValueAccessor for form integration</li><li><strong>Dual Mode</strong>: Supports both formControlName binding (reactive forms) and value binding mode</li></ol><h3>Why Internal FormControl?</h3><p>Material Design’s mat-form-field needs a FormControl to track error state and display the red border. Since we&#39;re using ControlValueAccessor, we create an internal FormControl that mirrors the parent control&#39;s state. This allows Material to properly display errors and styling.</p><h3>Step 2: Building the Password Input Component</h3><p>Now we’ll create the main PasswordInputComponent that uses PasswordFieldComponent and adds password rules validation:</p><p><strong>shared/components/password-input/password-input.ts:</strong></p><pre>import { Component, input, output, signal, computed, effect } from &#39;@angular/core&#39;;<br>import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormControl, ReactiveFormsModule, Validators, AbstractControl, ValidationErrors, ValidatorFn } from &#39;@angular/forms&#39;;<br>import { MatFormFieldModule } from &#39;@angular/material/form-field&#39;;<br>import { MatInputModule } from &#39;@angular/material/input&#39;;<br>import { MatIconModule } from &#39;@angular/material/icon&#39;;<br>export interface PasswordRule {<br>  label: string;<br>  validator: (password: string) =&gt; boolean;<br>}<br>@Component({<br>  selector: &#39;app-password-input&#39;,<br>  imports: [<br>    ReactiveFormsModule,<br>    MatFormFieldModule,<br>    MatInputModule,<br>    MatIconModule,<br>  ],<br>  templateUrl: &#39;./password-input.html&#39;,<br>  styleUrl: &#39;./password-input.scss&#39;,<br>  providers: [<br>    {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: PasswordInputComponent,<br>      multi: true,<br>    },<br>  ],<br>})<br>export class PasswordInputComponent implements ControlValueAccessor {<br>  // Inputs<br>  label = input&lt;string&gt;(&#39;Password&#39;);<br>  placeholder = input&lt;string&gt;(&#39;Enter your password&#39;);<br>  showConfirmPassword = input&lt;boolean&gt;(false);<br>  showRules = input&lt;boolean&gt;(true);<br>  // Outputs<br>  passwordChange = output&lt;string&gt;();<br>  // Internal state<br>  password = signal&lt;string&gt;(&#39;&#39;);<br>  confirmPassword = signal&lt;string&gt;(&#39;&#39;);<br>  showPassword = signal&lt;boolean&gt;(false);<br>  showConfirmPasswordVisible = signal&lt;boolean&gt;(false);<br>  // Password rules<br>  passwordRules = signal&lt;PasswordRule[]&gt;([<br>    {<br>      label: &#39;At least 8 characters&#39;,<br>      validator: (pwd: string) =&gt; pwd.length &gt;= 8,<br>    },<br>    {<br>      label: &#39;No more than 128 characters&#39;,<br>      validator: (pwd: string) =&gt; pwd.length &lt;= 128,<br>    },<br>    {<br>      label: &#39;At least one uppercase letter&#39;,<br>      validator: (pwd: string) =&gt; /[A-Z]/.test(pwd),<br>    },<br>    {<br>      label: &#39;At least one lowercase letter&#39;,<br>      validator: (pwd: string) =&gt; /[a-z]/.test(pwd),<br>    },<br>    {<br>      label: &#39;At least one digit&#39;,<br>      validator: (pwd: string) =&gt; /[0-9]/.test(pwd),<br>    },<br>    {<br>      label: &#39;At least one special character&#39;,<br>      validator: (pwd: string) =&gt; /[!@#$%^&amp;*()_+\-=\[\]{};&#39;:&quot;\\|,.&lt;&gt;\/?]/.test(pwd),<br>    },<br>  ]);<br>  // Computed values<br>  ruleStatuses = computed(() =&gt; {<br>    const pwd = this.password();<br>    return this.passwordRules().map(rule =&gt; ({<br>      ...rule,<br>      isValid: rule.validator(pwd),<br>    }));<br>  });<br>  passwordsMatch = computed(() =&gt; {<br>    if (!this.showConfirmPassword()) {<br>      return true;<br>    }<br>    const pwd = this.password();<br>    const confirm = this.confirmPassword();<br>    return pwd === confirm &amp;&amp; pwd.length &gt; 0;<br>  });<br>  isPasswordValid = computed(() =&gt; {<br>    const pwd = this.password();<br>    if (!pwd) return false;<br>    return this.ruleStatuses().every(rule =&gt; rule.isValid);<br>  });<br>  // ControlValueAccessor implementation<br>  private onChange = (value: string) =&gt; {};<br>  onTouched = () =&gt; {};<br>  constructor() {<br>    // Emit password changes when password signal changes<br>    effect(() =&gt; {<br>      const pwd = this.password();<br>      if (this.onChange) {<br>        this.onChange(pwd);<br>        this.passwordChange.emit(pwd);<br>      }<br>    });<br>  }<br>  writeValue(value: string): void {<br>    if (value !== this.password()) {<br>      this.password.set(value || &#39;&#39;);<br>    }<br>  }<br>  registerOnChange(fn: (value: string) =&gt; void): void {<br>    this.onChange = fn;<br>  }<br>  registerOnTouched(fn: () =&gt; void): void {<br>    this.onTouched = fn;<br>  }<br>  setDisabledState(isDisabled: boolean): void {<br>    // Handle disabled state if needed<br>  }<br>  onPasswordInput(event: Event): void {<br>    const value = (event.target as HTMLInputElement).value;<br>    this.password.set(value);<br>    this.onTouched();<br>  }<br>  onConfirmPasswordInput(event: Event): void {<br>    const value = (event.target as HTMLInputElement).value;<br>    this.confirmPassword.set(value);<br>    this.onTouched();<br>  }<br>  togglePasswordVisibility(): void {<br>    this.showPassword.update(v =&gt; !v);<br>  }<br>  toggleConfirmPasswordVisibility(): void {<br>    this.showConfirmPasswordVisible.update(v =&gt; !v);<br>  }<br>  // Validator function for form integration<br>  static passwordValidator(): ValidatorFn {<br>    return (control: AbstractControl): ValidationErrors | null =&gt; {<br>      const password = control.value;<br>      if (!password) {<br>        return null; // Let required validator handle empty<br>      }<br>      const errors: ValidationErrors = {};<br>      if (password.length &lt; 8) {<br>        errors[&#39;minlength&#39;] = { requiredLength: 8, actualLength: password.length };<br>      }<br>      if (password.length &gt; 128) {<br>        errors[&#39;maxlength&#39;] = { requiredLength: 128, actualLength: password.length };<br>      }<br>      if (!/[A-Z]/.test(password)) {<br>        errors[&#39;hasUppercase&#39;] = true;<br>      }<br>      if (!/[a-z]/.test(password)) {<br>        errors[&#39;hasLowercase&#39;] = true;<br>      }<br>      if (!/[0-9]/.test(password)) {<br>        errors[&#39;hasDigit&#39;] = true;<br>      }<br>      if (!/[!@#$%^&amp;*()_+\-=\[\]{};&#39;:&quot;\\|,.&lt;&gt;\/?]/.test(password)) {<br>        errors[&#39;hasSpecialChar&#39;] = true;<br>      }<br>      return Object.keys(errors).length &gt; 0 ? errors : null;<br>    };<br>  }<br>}</pre><h3>Key Features</h3><ol><li><strong>ControlValueAccessor</strong>: Enables integration with reactive forms</li><li><strong>Angular Signals</strong>: Reactive state management with signals</li><li><strong>Computed Signals</strong>: Automatic recalculation of rule statuses</li><li><strong>Input Signals</strong>: Modern Angular 21 input API</li><li><strong>Output Signals</strong>: Event emission for password changes</li><li><strong>Static Validator</strong>: Form validator function for parent forms</li><li><strong>Effect</strong>: Automatic synchronization with form control</li></ol><h3>Step 2: Template with Visual Feedback</h3><p>The PasswordInputComponent template uses PasswordFieldComponent for the actual password inputs:</p><p><strong>shared/components/password-input/password-input.html:</strong></p><pre>&lt;div class=&quot;password-input-container&quot;&gt;<br>  &lt;app-password-field<br>    [label]=&quot;label()&quot;<br>    [placeholder]=&quot;placeholder()&quot;<br>    [value]=&quot;password()&quot;<br>    (valueChange)=&quot;onPasswordInput($event)&quot;<br>    (touched)=&quot;onTouched()&quot;&gt;<br>  &lt;/app-password-field&gt;<br>  @if (showConfirmPassword()) {<br>    &lt;app-password-field<br>      label=&quot;Confirm Password&quot;<br>      placeholder=&quot;Confirm your password&quot;<br>      [value]=&quot;confirmPassword()&quot;<br>      (valueChange)=&quot;onConfirmPasswordInput($event)&quot;<br>      (touched)=&quot;onTouched()&quot;&gt;<br>    &lt;/app-password-field&gt;<br>  }<br>  @if (showRules() &amp;&amp; password()) {<br>    &lt;div class=&quot;password-rules&quot;&gt;<br>      &lt;div class=&quot;password-rules-title&quot;&gt;Password requirements:&lt;/div&gt;<br>      &lt;div class=&quot;password-rules-list&quot;&gt;<br>        @for (rule of ruleStatuses(); track rule.label) {<br>          &lt;div class=&quot;password-rule-item&quot; [class.valid]=&quot;rule.isValid&quot; [class.invalid]=&quot;!rule.isValid&quot;&gt;<br>            &lt;mat-icon class=&quot;rule-icon&quot;&gt;<br>              {{ rule.isValid ? &#39;check_circle&#39; : &#39;cancel&#39; }}<br>            &lt;/mat-icon&gt;<br>            &lt;span class=&quot;rule-label&quot;&gt;{{ rule.label }}&lt;/span&gt;<br>          &lt;/div&gt;<br>        }<br>      &lt;/div&gt;<br>      @if (showConfirmPassword()) {<br>        &lt;div class=&quot;password-rule-item&quot; [class.valid]=&quot;passwordsMatch()&quot; [class.invalid]=&quot;!passwordsMatch()&quot;&gt;<br>          &lt;mat-icon class=&quot;rule-icon&quot;&gt;<br>            {{ passwordsMatch() ? &#39;check_circle&#39; : &#39;cancel&#39; }}<br>          &lt;/mat-icon&gt;<br>          &lt;span class=&quot;rule-label&quot;&gt;Passwords match&lt;/span&gt;<br>        &lt;/div&gt;<br>      }<br>    &lt;/div&gt;<br>  }<br>&lt;/div&gt;</pre><p>When used with formControlName in a reactive form, the PasswordFieldComponent automatically handles form integration:</p><p><strong>features/auth/login/login.html:</strong></p><pre>&lt;app-password-field<br>  label=&quot;Password&quot;<br>  placeholder=&quot;Enter your password&quot;<br>  formControlName=&quot;password&quot;&gt;<br>&lt;/app-password-field&gt;</pre><h3>Template Features</h3><ol><li><strong>Component Composition</strong>: Uses PasswordFieldComponent for password inputs</li><li><strong>Conditional Rendering</strong>: Uses @if and @for for dynamic content</li><li><strong>Visual Feedback</strong>: Green checkmarks for valid rules, red X for invalid</li><li><strong>Password Visibility Toggle</strong>: Eye icon to show/hide password (handled by PasswordFieldComponent)</li><li><strong>Confirm Password</strong>: Optional second field with matching validation</li><li><strong>Material Design</strong>: Uses Material form fields and icons</li><li><strong>Accessibility</strong>: ARIA labels for screen readers</li><li><strong>Automatic Error Display</strong>: PasswordFieldComponent automatically shows validation errors</li></ol><h3>Step 3: Understanding the Internal FormControl Pattern</h3><p>The PasswordFieldComponent uses an important pattern for Material Design integration. Since Material&#39;s mat-form-field needs a FormControl to track error state and display the red border, we create an internal FormControl that mirrors the parent control&#39;s state:</p><pre>// Create a FormControl that mirrors the parent control for Material to track<br>internalFormControl = new FormControl(&#39;&#39;);<br>private syncControlState(): void {<br>  const c = this.control;<br>  if (c) {<br>    // Sync errors to internal FormControl so Material can see them<br>    this.internalFormControl.setErrors(c.errors);<br>    // Mark as touched/dirty to match parent<br>    if (c.touched &amp;&amp; !this.internalFormControl.touched) {<br>      this.internalFormControl.markAsTouched();<br>    }<br>    if (c.dirty &amp;&amp; !this.internalFormControl.dirty) {<br>      this.internalFormControl.markAsDirty();<br>    }<br>  }<br>}</pre><p>In the template, we bind the input to this internal FormControl:</p><pre>&lt;input<br>  matInput<br>  [formControl]=&quot;internalFormControl&quot;<br>  (input)=&quot;handleInput($event)&quot;<br>  (blur)=&quot;handleBlur()&quot;<br>/&gt;</pre><p>This allows Material Design to:</p><ul><li>Display the red border when the control is invalid</li><li>Show error messages automatically</li><li>Track touched/dirty states for proper error display timing</li></ul><h3>Step 4: Styling the Component</h3><p>We’ll style the component with Material Design principles:</p><p><strong>shared/components/password-input/password-input.scss:</strong></p><pre>.password-input-container {<br>  width: 100%;<br>}<br>.password-rules {<br>  margin-top: 8px;<br>  padding: 12px;<br>  background-color: var(--mat-sys-surface-variant);<br>  border-radius: 4px;<br>}<br>.password-rules-title {<br>  font-size: 0.875rem;<br>  font-weight: 500;<br>  color: var(--mat-sys-on-surface-variant);<br>  margin-bottom: 8px;<br>}<br>.password-rules-list {<br>  display: flex;<br>  flex-direction: column;<br>  gap: 6px;<br>  margin-bottom: 6px;<br>}<br>.password-rule-item {<br>  display: flex;<br>  align-items: center;<br>  gap: 8px;<br>  font-size: 0.875rem;<br>  transition: color 0.2s ease;<br>  &amp;.valid {<br>    color: var(--mat-sys-primary);<br>    .rule-icon {<br>      color: var(--mat-sys-primary);<br>    }<br>  }<br>  &amp;.invalid {<br>    color: var(--mat-sys-error);<br>    .rule-icon {<br>      color: var(--mat-sys-error);<br>    }<br>  }<br>}<br>.rule-icon {<br>  font-size: 18px;<br>  width: 18px;<br>  height: 18px;<br>  transition: color 0.2s ease;<br>}<br>.rule-label {<br>  line-height: 1.4;<br>}<br>// Style the visibility toggle buttons<br>button[mat-icon-button][matSuffix] {<br>  cursor: pointer;<br>  outline: none;<br>  border: none;<br>  background-color: transparent !important;<br>  margin-right: 6px;<br>  &amp;:focus {<br>    outline: none;<br>    background-color: transparent !important;<br>  }<br>  &amp;:focus-visible {<br>    outline: 2px solid var(--mat-sys-primary);<br>    outline-offset: 2px;<br>    background-color: transparent !important;<br>  }<br>  &amp;:hover {<br>    background-color: transparent !important;<br>  }<br>  // Make the eyeball icon match the lock icon color<br>  mat-icon {<br>    color: var(--mat-sys-on-surface-variant);<br>  }<br>}</pre><h3>Styling Features</h3><ol><li><strong>Material Design Variables</strong>: Uses Material 3 design tokens</li><li><strong>Color Coding</strong>: Green for valid, red for invalid rules</li><li><strong>Smooth Transitions</strong>: Color transitions for better UX</li><li><strong>Transparent Buttons</strong>: Visibility toggle buttons with transparent background</li><li><strong>Accessibility</strong>: Focus-visible states for keyboard navigation</li><li><strong>Consistent Spacing</strong>: Proper gaps and margins</li></ol><h3>Step 5: Using the Component in Forms</h3><p>We’ll integrate the component into the sign up form:</p><p><strong>features/auth/signup/signup.ts:</strong></p><pre>import { PasswordInputComponent } from &#39;../../../shared/components/password-input/password-input&#39;;<br>import { AuthService as ApiAuthService } from &#39;../../../core/api/api/auth.service&#39;;<br>import { AuthService } from &#39;../../../core/services/auth&#39;;<br>import { LoginDto } from &#39;../../../core/api/model/login-dto&#39;;<br>@Component({<br>  selector: &#39;app-signup&#39;,<br>  imports: [<br>    // ... other imports<br>    PasswordInputComponent,<br>    ReactiveFormsModule,<br>  ],<br>  // ...<br>})<br>export class Signup extends BaseComponent implements OnInit {<br>  private apiAuthService = inject(ApiAuthService);<br>  private authService = inject(AuthService);<br>  <br>  signupForm = this.fb.group({<br>    email: [&#39;&#39;, [Validators.required, Validators.email, Validators.maxLength(256)]],<br>    password: [&#39;&#39;, [Validators.required, PasswordInputComponent.passwordValidator()]],<br>    firstName: [&#39;&#39;, [Validators.required, Validators.maxLength(100)]],<br>    lastName: [&#39;&#39;, [Validators.required, Validators.maxLength(100)]],<br>  });<br>  ngOnInit(): void {<br>    // Automatically subscribe to signup attempts<br>    this.signupSubject<br>      .pipe(<br>        takeUntil(this.destroyed$),<br>        switchMap((createUserDto) =&gt;<br>          this.userService.apiUserPost(createUserDto).pipe(<br>            switchMap((response) =&gt; {<br>              // After successful signup, automatically log the user in<br>              this.successMessage.set(&#39;Account created successfully! Logging you in...&#39;);<br>              <br>              const loginDto: LoginDto = {<br>                email: createUserDto.email,<br>                password: createUserDto.password,<br>              };<br>              <br>              // Call login API with the same credentials<br>              return this.apiAuthService.apiAuthLoginPost(loginDto).pipe(<br>                tap((loginResponse) =&gt; {<br>                  // Handle successful login - store tokens and set up refresh timer<br>                  this.authService.handleLogin(loginResponse);<br>                  <br>                  // Navigate to home page<br>                  this.router.navigate([&#39;/&#39;]);<br>                }),<br>                catchError((loginError) =&gt; {<br>                  // If auto-login fails, redirect to login page<br>                  this.router.navigate([&#39;/login&#39;], {<br>                    queryParams: { registered: &#39;true&#39; }<br>                  });<br>                  return EMPTY;<br>                })<br>              );<br>            }),<br>            // ... error handling<br>          )<br>        )<br>      )<br>      .subscribe();<br>  }<br>  // ... rest of component<br>}</pre><p><strong>features/auth/signup/signup.html:</strong></p><pre>&lt;form [formGroup]=&quot;signupForm&quot; (ngSubmit)=&quot;onSubmit()&quot; class=&quot;d-flex flex-column gap-4&quot;&gt;<br>  &lt;!-- Email, First Name, Last Name fields --&gt;<br>  <br>  &lt;app-password-input<br>    formControlName=&quot;password&quot;<br>    [showConfirmPassword]=&quot;true&quot;<br>    [showRules]=&quot;true&quot;<br>    label=&quot;Password&quot;<br>    placeholder=&quot;Enter your password&quot;&gt;<br>  &lt;/app-password-input&gt;<br>  &lt;button mat-raised-button color=&quot;primary&quot; type=&quot;submit&quot; [disabled]=&quot;signupForm.invalid || isLoading()&quot;&gt;<br>    Sign Up<br>  &lt;/button&gt;<br>&lt;/form&gt;</pre><h3>Integration Features</h3><ol><li><strong>Form Control Binding</strong>: Uses formControlName for reactive forms</li><li><strong>Static Validator</strong>: Uses PasswordInputComponent.passwordValidator()</li><li><strong>Configurable Options</strong>: showConfirmPassword and showRules inputs</li><li><strong>Custom Labels</strong>: Optional label and placeholder customization</li><li><strong>Automatic Login</strong>: After successful signup, the user is automatically logged in using the same credentials, providing a seamless user experience without requiring a separate login step</li><li><strong>Automatic Login</strong>: After successful signup, the user is automatically logged in using the same credentials, providing a seamless user experience</li></ol><h3>Step 6: Understanding ControlValueAccessor</h3><p>ControlValueAccessor is an interface that allows custom form controls to integrate with Angular&#39;s reactive forms:</p><pre>interface ControlValueAccessor {<br>  writeValue(value: any): void;           // Called when form control value changes<br>  registerOnChange(fn: Function): void;   // Register callback for value changes<br>  registerOnTouched(fn: Function): void; // Register callback for touched state<br>  setDisabledState(isDisabled: boolean): void; // Handle disabled state<br>}</pre><h3>How It Works</h3><ol><li><strong>writeValue</strong>: Angular calls this when the form control value is set programmatically</li><li><strong>registerOnChange</strong>: Angular provides a callback function to notify when the value changes</li><li><strong>registerOnTouched</strong>: Angular provides a callback function to mark the control as touched</li><li><strong>setDisabledState</strong>: Angular calls this when the form control is disabled/enabled</li></ol><h3>Computed Signals for Reactive Validation</h3><p>We use computed signals to automatically recalculate validation status:</p><pre>ruleStatuses = computed(() =&gt; {<br>  const pwd = this.password();<br>  return this.passwordRules().map(rule =&gt; ({<br>    ...rule,<br>    isValid: rule.validator(pwd),<br>  }));<br>});<br>passwordsMatch = computed(() =&gt; {<br>  if (!this.showConfirmPassword()) {<br>    return true;<br>  }<br>  const pwd = this.password();<br>  const confirm = this.confirmPassword();<br>  return pwd === confirm &amp;&amp; pwd.length &gt; 0;<br>});</pre><h3>Benefits</h3><ol><li><strong>Automatic Updates</strong>: Recalculates when password signal changes</li><li><strong>Performance</strong>: Only recalculates when dependencies change</li><li><strong>Reactive</strong>: Template automatically updates when computed values change</li><li><strong>Type Safe</strong>: TypeScript ensures type safety</li></ol><h3>Password Rules Configuration</h3><p>The component includes configurable password rules:</p><pre>passwordRules = signal&lt;PasswordRule[]&gt;([<br>  {<br>    label: &#39;At least 8 characters&#39;,<br>    validator: (pwd: string) =&gt; pwd.length &gt;= 8,<br>  },<br>  {<br>    label: &#39;No more than 128 characters&#39;,<br>    validator: (pwd: string) =&gt; pwd.length &lt;= 128,<br>  },<br>  {<br>    label: &#39;At least one uppercase letter&#39;,<br>    validator: (pwd: string) =&gt; /[A-Z]/.test(pwd),<br>  },<br>  {<br>    label: &#39;At least one lowercase letter&#39;,<br>    validator: (pwd: string) =&gt; /[a-z]/.test(pwd),<br>  },<br>  {<br>    label: &#39;At least one digit&#39;,<br>    validator: (pwd: string) =&gt; /[0-9]/.test(pwd),<br>  },<br>  {<br>    label: &#39;At least one special character&#39;,<br>    validator: (pwd: string) =&gt; /[!@#$%^&amp;*()_+\-=\[\]{};&#39;:&quot;\\|,.&lt;&gt;\/?]/.test(pwd),<br>  },<br>]);</pre><h3>Rule Structure</h3><ul><li><strong>Label</strong>: Human-readable description</li><li><strong>Validator</strong>: Function that returns true if rule is satisfied</li><li><strong>Flexible</strong>: Easy to add, remove, or modify rules</li></ul><h3>Best Practices</h3><h3>1. ControlValueAccessor Implementation</h3><ul><li>Always implement all four methods</li><li>Call onChange when value changes internally</li><li>Call onTouched when user interacts with the control</li><li>Handle disabled state appropriately</li></ul><h3>2. Signal Usage</h3><ul><li>Use signals for reactive state</li><li>Use computed signals for derived values</li><li>Use effects sparingly (only for side effects)</li><li>Keep signals focused and single-purpose</li></ul><h3>3. Accessibility</h3><ul><li>Include ARIA labels for icon buttons</li><li>Ensure keyboard navigation works</li><li>Provide visual feedback for all states</li><li>Test with screen readers</li></ul><h3>4. Form Integration</h3><ul><li>Provide static validator functions</li><li>Support both template-driven and reactive forms</li><li>Handle validation errors gracefully</li><li>Emit events for parent components</li></ul><h3>5. Styling</h3><ul><li>Use Material Design tokens</li><li>Provide clear visual feedback</li><li>Ensure sufficient color contrast</li><li>Support focus states</li></ul><h3>Testing the Component</h3><ol><li><strong>Start the Application</strong>: npm start</li><li><strong>Navigate to Sign Up</strong>: Go to /signup</li><li><strong>Test Password Input</strong>: Type in password field</li><li><strong>Verify Rules</strong>: Check that rules update in real-time</li><li><strong>Test Confirm Password</strong>: Verify matching validation</li><li><strong>Test Visibility Toggle</strong>: Click eye icon to show/hide password</li><li><strong>Test Form Validation</strong>: Submit form with invalid password</li><li><strong>Test Form Submission</strong>: Submit form with valid password</li><li><strong>Test Automatic Login</strong>: After successful signup, verify that you are automatically logged in and redirected to the home page</li></ol><h3>Common Issues and Solutions</h3><h3>Issue: Component not updating form control</h3><p><strong>Solution</strong>: Ensure onChange callback is called when password changes</p><h3>Issue: Validation not working</h3><p><strong>Solution</strong>: Verify passwordValidator() is added to form control validators</p><h3>Issue: Rules not showing</h3><p><strong>Solution</strong>: Check that showRules input is true and password has a value</p><h3>Issue: Confirm password not validating</h3><p><strong>Solution</strong>: Ensure showConfirmPassword input is true</p><h3>Issue: Styling conflicts</h3><p><strong>Solution</strong>: Check CSS specificity and ensure component styles are scoped</p><h3>Extending the Component</h3><p>The component can be extended with additional features:</p><pre>// Add custom password rules<br>passwordRules = signal&lt;PasswordRule[]&gt;([<br>  // ... existing rules<br>  {<br>    label: &#39;No common passwords&#39;,<br>    validator: (pwd: string) =&gt; ![&#39;password&#39;, &#39;12345678&#39;].includes(pwd.toLowerCase()),<br>  },<br>]);<br>// Add password strength indicator<br>passwordStrength = computed(() =&gt; {<br>  const validRules = this.ruleStatuses().filter(r =&gt; r.isValid).length;<br>  const totalRules = this.passwordRules().length;<br>  return (validRules / totalRules) * 100;<br>});</pre><h3>Project Structure</h3><p>After completing this setup:</p><pre>src/app/<br>├── shared/<br>│   └── components/<br>│       ├── password-field/<br>│       │   ├── password-field.ts<br>│       │   ├── password-field.html<br>│       │   └── password-field.scss<br>│       └── password-input/<br>│           ├── password-input.ts<br>│           ├── password-input.html<br>│           └── password-input.scss<br>└── features/<br>    └── auth/<br>        ├── login/<br>        │   └── login.html (uses &lt;app-password-field&gt;)<br>        └── signup/<br>            ├── signup.ts (uses PasswordInputComponent)<br>            └── signup.html (uses &lt;app-password-input&gt;)</pre><h3>Conclusion</h3><p>We’ve successfully implemented:</p><ul><li>✅ Reusable password field component (PasswordFieldComponent) for single password inputs</li><li>✅ Reusable password input component (PasswordInputComponent) with rules and confirm password</li><li>✅ ControlValueAccessor integration with reactive forms</li><li>✅ Internal FormControl pattern for Material Design integration</li><li>✅ Automatic error display and red border styling</li><li>✅ Visual feedback with checkmarks/X icons</li><li>✅ Password rules validation</li><li>✅ Confirm password functionality</li><li>✅ Password visibility toggles</li><li>✅ Angular Signals for reactive state</li><li>✅ Static validator function for form integration</li><li>✅ Material Design styling</li><li>✅ Accessibility features</li><li>✅ Configurable options (show rules, show confirm password)</li><li>✅ Component composition for maximum reusability</li><li>✅ Automatic login after successful signup for seamless user experience</li></ul><p>The password input component provides a professional, user-friendly way to handle password input with real-time validation feedback. It’s reusable across the application and integrates seamlessly with Angular’s reactive forms system.</p><p>In the next blog post, we’ll continue building out additional features and components.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, Angular Material, Reusable Components, ControlValueAccessor, Form Validation, Angular Signals, Reactive Forms, Component Architecture, User Experience, Accessibility, Material Design, Password Validation, Custom Form Controls, Web Development, UI Development</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cacd04f64a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Server-Side Configuration & Sign Up Link]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-server-side-configuration-sign-up-link-7b648dbbe765?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b648dbbe765</guid>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 03:27:14 GMT</pubDate>
            <atom:updated>2025-12-31T03:27:14.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VNukkZOYMfSVRZ-8WJT7g.png" /></figure><p><em>Implementing server-side configuration endpoint and conditional sign up link on the login screen</em></p><h3>Introduction</h3><p>In our previous post, we implemented runtime configuration loading from a JSON file and enhanced the footer with environment and version badges. Now we’ll extend our configuration system to include server-side configuration. We’ll create an API endpoint that provides configuration values like feature flags, and integrate it into our Angular application. We’ll then use this server configuration to conditionally display a “Sign Up” link on the login screen based on whether user registration is allowed.</p><h3>Why Server-Side Configuration?</h3><p>Server-side configuration provides several advantages over client-only configuration:</p><ol><li><strong>Feature Flags</strong>: Enable/disable features without code deployment</li><li><strong>Centralized Control</strong>: Manage configuration from the server</li><li><strong>Security</strong>: Sensitive settings stay on the server</li><li><strong>Dynamic Updates</strong>: Change behavior without client updates</li><li><strong>Environment Consistency</strong>: Same client code works across environments</li><li><strong>Operational Flexibility</strong>: DevOps can control features independently</li></ol><h3>Architecture Overview</h3><p>Our server-side configuration system consists of:</p><pre>App Starts<br>    ↓<br>APP_INITIALIZER loads client config (config.json)<br>    ↓<br>API base URL configured<br>    ↓<br>APP_INITIALIZER loads server config from API<br>    ↓<br>ConfigService stores server configuration<br>    ↓<br>Login component checks allowSignUp flag<br>    ↓<br>Sign Up link conditionally displayed</pre><h3>Step 1: Creating the Server Configuration DTO</h3><p>We’ll create a DTO to represent server-side configuration:</p><p><strong>Portal.Api.Services/DTOs/AppConfigDto.cs:</strong></p><pre>namespace Portal.Api.Services.DTOs;<br>/// &lt;summary&gt;<br>/// Application configuration DTO that provides client-side configuration values<br>/// &lt;/summary&gt;<br>public class AppConfigDto<br>{<br>    /// &lt;summary&gt;<br>    /// Whether user registration/sign up is allowed<br>    /// &lt;/summary&gt;<br>    public bool AllowSignUp { get; set; } = true;<br>}</pre><p>This DTO:</p><ul><li>Uses a simple boolean for AllowSignUp</li><li>Defaults to true for open registration</li><li>Can be extended with additional configuration properties</li></ul><h3>Step 2: Creating the Configuration Controller</h3><p>We’ll create a controller to serve configuration values:</p><p><strong>Portal.Api/Controllers/ConfigController.cs:</strong></p><pre>using Microsoft.AspNetCore.Mvc;<br>using Portal.Api.Services.DTOs;<br>namespace Portal.Api.Controllers;<br>/// &lt;summary&gt;<br>/// Configuration controller that provides application configuration to clients<br>/// &lt;/summary&gt;<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>[Produces(&quot;application/json&quot;)]<br>public class ConfigController : ControllerBase<br>{<br>    /// &lt;summary&gt;<br>    /// Gets application configuration values<br>    /// &lt;/summary&gt;<br>    /// &lt;returns&gt;Application configuration&lt;/returns&gt;<br>    /// &lt;response code=&quot;200&quot;&gt;Configuration retrieved successfully&lt;/response&gt;<br>    [HttpGet]<br>    [ProducesResponseType(typeof(AppConfigDto), StatusCodes.Status200OK)]<br>    public IActionResult GetConfig()<br>    {<br>        var config = new AppConfigDto<br>        {<br>            AllowSignUp = true // Default to true, can be configured via appsettings.json in the future<br>        };<br>        return Ok(config);<br>    }<br>}</pre><h3>Key Features</h3><ol><li><strong>Public Endpoint</strong>: No authentication required (configuration is public)</li><li><strong>Simple Response</strong>: Returns JSON with configuration values</li><li><strong>Extensible</strong>: Easy to add more configuration properties</li><li><strong>Swagger Documentation</strong>: Automatically documented in Swagger UI</li></ol><h3>Step 3: Extending the Config Service</h3><p>We’ll extend our Angular ConfigService to load server configuration:</p><p><strong>core/services/config.service.ts:</strong></p><pre>/**<br> * Server-side configuration interface (from API)<br> */<br>export interface ServerConfig {<br>  allowSignUp: boolean;<br>  [key: string]: any; // Allow additional server config properties<br>}<br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ConfigService {<br>  private config: AppConfig | null = null;<br>  private serverConfig: ServerConfig | null = null;<br>  private configLoaded = false;<br>  private serverConfigLoaded = false;<br>  constructor(private http: HttpClient) {}<br>  /**<br>   * Load server-side configuration from API<br>   * This should be called after the API base URL is configured<br>   * @returns Promise that resolves when server config is loaded<br>   */<br>  loadServerConfig(): Promise&lt;void&gt; {<br>    if (this.serverConfigLoaded) {<br>      return Promise.resolve();<br>    }<br>    const apiBaseUrl = this.getApiBaseUrl();<br>    const configUrl = apiBaseUrl ? `${apiBaseUrl}/api/config` : &#39;/api/config&#39;;<br>    return firstValueFrom(this.http.get&lt;ServerConfig&gt;(configUrl))<br>      .then((config) =&gt; {<br>        this.serverConfig = config;<br>        this.serverConfigLoaded = true;<br>        console.log(&#39;Server configuration loaded:&#39;, config);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&#39;Failed to load server configuration:&#39;, error);<br>        // Provide default server configuration if API call fails<br>        this.serverConfig = {<br>          allowSignUp: true,<br>        };<br>        this.serverConfigLoaded = true;<br>        console.warn(&#39;Using default server configuration&#39;);<br>      });<br>  }<br>  /**<br>   * Get whether user sign up is allowed<br>   * @returns True if sign up is allowed, false otherwise<br>   */<br>  getAllowSignUp(): boolean {<br>    return this.serverConfig?.allowSignUp ?? true;<br>  }<br>  getServerConfig(): ServerConfig | null {<br>    return this.serverConfig;<br>  }<br>  isServerConfigLoaded(): boolean {<br>    return this.serverConfigLoaded;<br>  }<br>}</pre><h3>Key Features</h3><ol><li><strong>Separate Storage</strong>: Server config stored separately from client config</li><li><strong>Error Handling</strong>: Falls back to defaults if API call fails</li><li><strong>Type Safety</strong>: TypeScript interface for server configuration</li><li><strong>Status Tracking</strong>: Tracks whether server config has been loaded</li></ol><h3>Step 4: Updating the App Initializer</h3><p>We’ll update the app initializer to load both client and server configuration:</p><p><strong>app.config.ts:</strong></p><pre>/**<br> * App initializer function that loads configuration before the app starts<br> * Loads both client config (config.json) and server config (API endpoint)<br> */<br>export function initializeApp(configService: ConfigService): () =&gt; Promise&lt;void&gt; {<br>  return async () =&gt; {<br>    // First load client config (config.json) to get API base URL<br>    await configService.loadConfig();<br>    // Then load server config from API<br>    await configService.loadServerConfig();<br>  };<br>}</pre><h3>Loading Sequence</h3><ol><li><strong>Client Config First</strong>: Loads config.json to get API base URL</li><li><strong>Server Config Second</strong>: Uses API base URL to fetch server configuration</li><li><strong>Sequential Loading</strong>: Ensures API URL is available before making API call</li><li><strong>Error Resilience</strong>: Each step has its own error handling</li></ol><h3>Step 5: Updating the Login Component</h3><p>We’ll update the login component to conditionally show the sign up link:</p><p><strong>features/auth/login/login.ts:</strong></p><pre>import { ConfigService } from &#39;../../../core/services/config.service&#39;;<br>import { RouterLink } from &#39;@angular/router&#39;;<br>@Component({<br>  selector: &#39;app-login&#39;,<br>  imports: [<br>    // ... other imports<br>    RouterLink,<br>  ],<br>  // ...<br>})<br>export class Login extends BaseComponent implements OnInit {<br>  private configService = inject(ConfigService);<br>  /**<br>   * Get whether sign up is allowed from server configuration<br>   */<br>  get allowSignUp(): boolean {<br>    return this.configService.getAllowSignUp();<br>  }<br>  // ... rest of component<br>}</pre><p><strong>features/auth/login/login.html:</strong></p><pre>&lt;mat-card-content&gt;<br>  &lt;form [formGroup]=&quot;loginForm&quot; (ngSubmit)=&quot;onSubmit()&quot; class=&quot;d-flex flex-column gap-4&quot;&gt;<br>    &lt;!-- Login form fields --&gt;<br>    <br>    &lt;button mat-raised-button color=&quot;primary&quot; type=&quot;submit&quot; class=&quot;w-100&quot;&gt;<br>      Sign In<br>    &lt;/button&gt;<br>  &lt;/form&gt;<br>  @if (allowSignUp) {<br>    &lt;div class=&quot;d-flex justify-content-center mt-4&quot;&gt;<br>      &lt;p class=&quot;mb-0 text-sm text-on-surface-variant&quot;&gt;<br>        Don&#39;t have an account?<br>        &lt;a routerLink=&quot;/signup&quot; class=&quot;text-primary text-decoration-none&quot;&gt;Sign Up&lt;/a&gt;<br>      &lt;/p&gt;<br>    &lt;/div&gt;<br>  }<br>&lt;/mat-card-content&gt;</pre><h3>Template Features</h3><ol><li><strong>Conditional Rendering</strong>: Uses @if to show link only when allowed</li><li><strong>Material Design Styling</strong>: Uses Material color classes</li><li><strong>Router Link</strong>: Uses Angular Router for navigation</li><li><strong>Centered Layout</strong>: Link centered below the form</li><li><strong>Accessible</strong>: Clear text and proper link styling</li></ol><h3>Understanding the Configuration Flow</h3><p>The complete configuration loading process:</p><pre>1. App bootstrap starts<br>   ↓<br>2. APP_INITIALIZER executes<br>   ↓<br>3. ConfigService.loadConfig() called<br>   ↓<br>4. HTTP GET request to /config.json<br>   ↓<br>5. Client config stored (includes API base URL)<br>   ↓<br>6. ConfigService.loadServerConfig() called<br>   ↓<br>7. HTTP GET request to /api/config (using API base URL)<br>   ↓<br>8. Server config stored (includes allowSignUp)<br>   ↓<br>9. App initialization continues<br>   ↓<br>10. Components can access both configs via ConfigService</pre><h3>Using Server Configuration in Components</h3><p>Components can access server configuration through the ConfigService:</p><pre>import { ConfigService } from &#39;./core/services/config.service&#39;;<br>export class MyComponent {<br>  private configService = inject(ConfigService);<br>  ngOnInit(): void {<br>    const allowSignUp = this.configService.getAllowSignUp();<br>    <br>    if (allowSignUp) {<br>      // Show sign up UI<br>    }<br>  }<br>}</pre><h3>Extending Server Configuration</h3><p>To add more configuration properties:</p><p><strong>Backend (AppConfigDto.cs):</strong></p><pre>public class AppConfigDto<br>{<br>    public bool AllowSignUp { get; set; } = true;<br>    public bool AllowPasswordReset { get; set; } = true;<br>    public int MaxLoginAttempts { get; set; } = 5;<br>    public string MaintenanceMessage { get; set; } = string.Empty;<br>}</pre><p><strong>Frontend (config.service.ts):</strong></p><pre>export interface ServerConfig {<br>  allowSignUp: boolean;<br>  allowPasswordReset: boolean;<br>  maxLoginAttempts: number;<br>  maintenanceMessage: string;<br>}<br>getAllowPasswordReset(): boolean {<br>  return this.serverConfig?.allowPasswordReset ?? true;<br>}</pre><h3>Best Practices</h3><h3>1. Configuration Loading</h3><ul><li>Load client config before server config</li><li>Handle errors gracefully with defaults</li><li>Log configuration loading for debugging</li><li>Cache configuration to avoid repeated requests</li></ul><h3>2. Server Configuration</h3><ul><li>Keep configuration simple and focused</li><li>Use sensible defaults</li><li>Document all configuration properties</li><li>Consider caching on the server side</li></ul><h3>3. Feature Flags</h3><ul><li>Use boolean flags for simple on/off features</li><li>Consider more complex flags for advanced scenarios</li><li>Test both enabled and disabled states</li><li>Document feature flag behavior</li></ul><h3>4. Conditional Rendering</h3><ul><li>Use Angular’s @if for conditional display</li><li>Keep conditional logic simple</li><li>Provide fallback UI when appropriate</li><li>Test all conditional branches</li></ul><h3>Testing the Implementation</h3><ol><li><strong>Start the API</strong>: docker-compose up api</li><li><strong>Start the UI</strong>: docker-compose up ui or npm start</li><li><strong>Check Config Endpoint</strong>: Visit http://localhost:8080/api/config in browser</li><li><strong>Verify Config Loading</strong>: Check browser console for “Server configuration loaded”</li><li><strong>Test Sign Up Link</strong>: Verify link appears on login screen</li><li><strong>Test Conditional Display</strong>: Change allowSignUp to false and verify link disappears</li></ol><h3>Common Issues and Solutions</h3><h3>Issue: Server config not loading</h3><p><strong>Solution</strong>: Verify API is running and /api/config endpoint is accessible</p><h3>Issue: Sign up link not appearing</h3><p><strong>Solution</strong>: Check that allowSignUp is true in server config and ConfigService is injected</p><h3>Issue: CORS errors when loading server config</h3><p><strong>Solution</strong>: Ensure API CORS is configured to allow requests from UI origin</p><h3>Issue: Config loads but link doesn’t update</h3><p><strong>Solution</strong>: Verify component is using getter method, not cached value</p><h3>Issue: API base URL not set when loading server config</h3><p><strong>Solution</strong>: Ensure client config loads before server config in initializer</p><h3>Project Structure</h3><p>After completing this setup:</p><pre>api/<br>├── Portal.Api/<br>│   └── Controllers/<br>│       └── ConfigController.cs<br>└── Portal.Api.Services/<br>    └── DTOs/<br>        └── AppConfigDto.cs</pre><pre>ui/src/app/<br>├── core/<br>│   └── services/<br>│       └── config.service.ts (updated)<br>├── features/<br>│   └── auth/<br>│       └── login/<br>│           ├── login.ts (updated)<br>│           └── login.html (updated)<br>└── app.config.ts (updated)</pre><h3>Conclusion</h3><p>We’ve successfully implemented:</p><ul><li>✅ Server-side configuration endpoint in API</li><li>✅ AppConfigDto with allowSignUp property</li><li>✅ ConfigService extension for server configuration</li><li>✅ Updated APP_INITIALIZER to load server config</li><li>✅ Conditional sign up link on login screen</li><li>✅ Material Design styling for the link</li><li>✅ Error handling with default values</li><li>✅ Type-safe configuration interfaces</li></ul><p>The application now supports server-side configuration, allowing feature flags and other settings to be controlled from the API. The sign up link conditionally appears based on server configuration, providing a clean way to enable or disable user registration without code changes.</p><p>In the next blog post, we’ll continue building out additional features and components.</p><p><strong>Tags</strong>: .NET Core, Angular, TypeScript, Server-Side Configuration, API Endpoints, Feature Flags, Configuration Management, Angular Material Links, Conditional Rendering, Client-Server Configuration Sync, Web Development, Backend Development, Frontend Development, ASP.NET Core, C#</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b648dbbe765" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Runtime Configuration & Footer Enhancements]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-runtime-configuration-footer-enhancements-1589fab6d5d3?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/1589fab6d5d3</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[runtime-configuration]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 02:47:12 GMT</pubDate>
            <atom:updated>2025-12-31T02:47:12.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnL4B9at0QcfwLagtddDLw.png" /></figure><p><em>Implementing runtime configuration loading and enhancing the footer with environment and version badges</em></p><h3>Introduction</h3><p>In our previous post, we built the user menu in the header with logout functionality. Now we’ll implement a runtime configuration system that loads settings from a JSON file before the app starts, allowing us to configure the API endpoint and other settings without rebuilding the application. We’ll also enhance the footer component to display environment and version information using Material Design badges.</p><h3>Why Runtime Configuration?</h3><p>Runtime configuration provides several advantages over build-time configuration:</p><ol><li><strong>Flexibility</strong>: Change settings without rebuilding the application</li><li><strong>Environment-Specific</strong>: Different configs for dev, staging, and production</li><li><strong>Deployment Simplicity</strong>: Update config file in deployment without code changes</li><li><strong>API Endpoint Management</strong>: Configure API URLs per environment</li><li><strong>Version Tracking</strong>: Display version information dynamically</li><li><strong>Operational Control</strong>: DevOps can update settings without developer intervention</li></ol><h3>Architecture Overview</h3><p>Our configuration system consists of:</p><pre>App Starts<br>    ↓<br>APP_INITIALIZER loads config.json via HTTP<br>    ↓<br>ConfigService stores configuration<br>    ↓<br>API base path configured from config<br>    ↓<br>App initializes with correct settings<br>    ↓<br>Footer displays environment and version from config</pre><h3>Step 1: Creating the Configuration Service</h3><p>We’ll create a service that loads configuration from a JSON file:</p><p><strong>core/services/config.service.ts:</strong></p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { firstValueFrom } from &#39;rxjs&#39;;<br>/**<br> * Application configuration interface<br> */<br>export interface AppConfig {<br>  apiBaseUrl: string;<br>  environment: string;<br>  version: string;<br>  appName?: string;<br>  [key: string]: any; // Allow additional config properties<br>}<br>/**<br> * Service that loads and provides application configuration from a JSON file.<br> * <br> * The configuration is loaded before the app initializes via APP_INITIALIZER.<br> * This allows the app to use configuration values (like API endpoints) during bootstrap.<br> */<br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ConfigService {<br>  private config: AppConfig | null = null;<br>  private configLoaded = false;<br>  constructor(private http: HttpClient) {}<br>  /**<br>   * Load configuration from config.json file<br>   * @returns Promise that resolves when config is loaded<br>   */<br>  loadConfig(): Promise&lt;void&gt; {<br>    if (this.configLoaded) {<br>      return Promise.resolve();<br>    }<br>    return firstValueFrom(this.http.get&lt;AppConfig&gt;(&#39;/config.json&#39;))<br>      .then((config) =&gt; {<br>        this.config = config;<br>        this.configLoaded = true;<br>        console.log(&#39;Application configuration loaded:&#39;, config);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&#39;Failed to load application configuration:&#39;, error);<br>        // Provide default configuration if file fails to load<br>        this.config = {<br>          apiBaseUrl: &#39;&#39;,<br>          environment: &#39;development&#39;,<br>          version: &#39;1.0.0&#39;,<br>        };<br>        this.configLoaded = true;<br>        console.warn(&#39;Using default configuration&#39;);<br>      });<br>  }<br>  getApiBaseUrl(): string {<br>    return this.config?.apiBaseUrl || &#39;&#39;;<br>  }<br>  getEnvironment(): string {<br>    return this.config?.environment || &#39;development&#39;;<br>  }<br>  getVersion(): string {<br>    return this.config?.version || &#39;1.0.0&#39;;<br>  }<br>  getAppName(): string {<br>    return this.config?.appName || &#39;Portal Starter Kit&#39;;<br>  }<br>  getConfigValue&lt;T = any&gt;(key: string): T | undefined {<br>    return this.config?.[key] as T | undefined;<br>  }<br>  getConfig(): AppConfig | null {<br>    return this.config;<br>  }<br>  isConfigLoaded(): boolean {<br>    return this.configLoaded;<br>  }<br>}</pre><h3>Key Features</h3><ol><li><strong>HTTP Loading</strong>: Loads config from /config.json via HTTP</li><li><strong>Error Handling</strong>: Falls back to defaults if config fails to load</li><li><strong>Type Safety</strong>: TypeScript interface for configuration</li><li><strong>Extensible</strong>: Supports additional custom properties</li><li><strong>Status Tracking</strong>: Tracks whether config has been loaded</li></ol><h3>Step 2: Creating the Configuration File</h3><p>We’ll create a JSON configuration file in the public folder:</p><p><strong>public/config.json:</strong></p><pre>{<br>  &quot;apiBaseUrl&quot;: &quot;&quot;,<br>  &quot;environment&quot;: &quot;development&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;appName&quot;: &quot;Portal Starter Kit&quot;<br>}</pre><h3>Configuration Properties</h3><ul><li><strong>apiBaseUrl</strong>: API base URL (empty string uses proxy in dev, full URL in production)</li><li><strong>environment</strong>: Environment name (development, staging, production)</li><li><strong>version</strong>: Application version number</li><li><strong>appName</strong>: Application display name</li></ul><h3>Step 3: Implementing APP_INITIALIZER</h3><p>We’ll use Angular’s APP_INITIALIZER to load configuration before the app starts:</p><p><strong>app.config.ts:</strong></p><pre>import { ApplicationConfig, APP_INITIALIZER, provideBrowserGlobalErrorListeners } from &#39;@angular/core&#39;;<br>import { provideHttpClient, withInterceptors } from &#39;@angular/common/http&#39;;<br>import { ConfigService } from &#39;./core/services/config.service&#39;;<br>import { BASE_PATH } from &#39;./core/api/variables&#39;;<br>/**<br> * App initializer function that loads configuration before the app starts<br> */<br>export function initializeApp(configService: ConfigService): () =&gt; Promise&lt;void&gt; {<br>  return () =&gt; configService.loadConfig();<br>}<br>/**<br> * Factory function to get API base path from config service<br> * The config should be loaded by APP_INITIALIZER before this is called<br> */<br>export function apiBasePathFactory(configService: ConfigService): string {<br>  if (!configService.isConfigLoaded()) {<br>    console.warn(&#39;Config not loaded yet, using default empty base path&#39;);<br>    return &#39;&#39;;<br>  }<br>  return configService.getApiBaseUrl();<br>}<br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])),<br>    // App initializer to load configuration before app starts<br>    {<br>      provide: APP_INITIALIZER,<br>      useFactory: initializeApp,<br>      deps: [ConfigService],<br>      multi: true,<br>    },<br>    // Configure API client base path using config service<br>    {<br>      provide: BASE_PATH,<br>      useFactory: apiBasePathFactory,<br>      deps: [ConfigService],<br>    },<br>    provideApi({})<br>  ]<br>};</pre><h3>How APP_INITIALIZER Works</h3><ol><li><strong>Execution Order</strong>: Runs before the app initializes</li><li><strong>Blocking</strong>: App startup waits until all initializers complete</li><li><strong>Multiple Initializers</strong>: Can have multiple initializers (hence multi: true)</li><li><strong>Dependency Injection</strong>: Has access to Angular’s DI system</li><li><strong>Promise-Based</strong>: Returns a promise that resolves when initialization is complete</li></ol><h3>Step 4: Enhancing the Footer Component</h3><p>We’ll update the footer to display environment and version information:</p><p><strong>shared/components/footer/footer.ts:</strong></p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { MatChipsModule } from &#39;@angular/material/chips&#39;;<br>import { ConfigService } from &#39;../../../core/services/config.service&#39;;<br>@Component({<br>  selector: &#39;app-footer&#39;,<br>  imports: [MatChipsModule],<br>  templateUrl: &#39;./footer.html&#39;,<br>  styleUrl: &#39;./footer.scss&#39;,<br>})<br>export class Footer {<br>  private configService = inject(ConfigService);<br>  <br>  currentYear = new Date().getFullYear();<br>  get environment(): string {<br>    return this.configService.getEnvironment();<br>  }<br>  get version(): string {<br>    return this.configService.getVersion();<br>  }<br>  get isProduction(): boolean {<br>    return this.environment.toLowerCase() === &#39;production&#39;;<br>  }<br>}</pre><p><strong>shared/components/footer/footer.html:</strong></p><pre>&lt;footer class=&quot;footer-container&quot;&gt;<br>  &lt;div class=&quot;d-flex align-items-center justify-content-start py-4 px-4 gap-3&quot;&gt;<br>    &lt;p class=&quot;my-0&quot;&gt;<br>      &amp;copy; {{ currentYear }} Portal Starter Kit. All rights reserved.<br>    &lt;/p&gt;<br>    @if (!isProduction) {<br>      &lt;mat-chip class=&quot;footer-badge&quot;&gt;<br>        {{ environment }}<br>      &lt;/mat-chip&gt;<br>    }<br>    &lt;mat-chip class=&quot;footer-badge&quot;&gt;<br>      v{{ version }}<br>    &lt;/mat-chip&gt;<br>  &lt;/div&gt;<br>&lt;/footer&gt;</pre><p><strong>shared/components/footer/footer.scss:</strong></p><pre>.footer-container {<br>  background-color: var(--mat-sys-surface-variant);<br>  color: var(--mat-sys-on-surface-variant);<br>  border-top: 1px solid var(--mat-sys-outline-variant);<br>  margin-top: auto;<br>}<br>.footer-badge {<br>  font-size: 0.75rem;<br>  height: 20px;<br>  padding: 0 8px;<br>  line-height: 20px;<br>}</pre><h3>Footer Features</h3><ol><li><strong>Left-Aligned</strong>: Content and badges aligned to the left</li><li><strong>Environment Badge</strong>: Only shows in non-production environments</li><li><strong>Version Badge</strong>: Always displays version number</li><li><strong>Material Design</strong>: Uses Material chips for badge styling</li><li><strong>Compact Size</strong>: Smaller font size (0.75rem) for subtle display</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PbgomQdVULs9MzW9WTLjw.png" /><figcaption>Our updated footer showing the version values from our config file</figcaption></figure><h3>Understanding the Configuration Flow</h3><p>The configuration loading process:</p><pre>1. App bootstrap starts<br>   ↓<br>2. APP_INITIALIZER executes<br>   ↓<br>3. ConfigService.loadConfig() called<br>   ↓<br>4. HTTP GET request to /config.json<br>   ↓<br>5. Config stored in ConfigService<br>   ↓<br>6. apiBasePathFactory() called (uses config)<br>   ↓<br>7. BASE_PATH provider configured<br>   ↓<br>8. App initialization continues<br>   ↓<br>9. Components can access config via ConfigService</pre><h3>Using Configuration in Components</h3><p>Components can access configuration through the ConfigService:</p><pre>import { ConfigService } from &#39;./core/services/config.service&#39;;<br>export class MyComponent {<br>  private configService = inject(ConfigService);<br>  ngOnInit(): void {<br>    const apiUrl = this.configService.getApiBaseUrl();<br>    const env = this.configService.getEnvironment();<br>    const version = this.configService.getVersion();<br>    <br>    // Get custom config value<br>    const customValue = this.configService.getConfigValue&lt;string&gt;(&#39;customKey&#39;);<br>  }<br>}</pre><h3>Environment-Specific Configuration</h3><h3>Development</h3><pre>{<br>  &quot;apiBaseUrl&quot;: &quot;&quot;,<br>  &quot;environment&quot;: &quot;development&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;<br>}</pre><ul><li>Empty apiBaseUrl uses Angular proxy</li><li>Environment badge shows “development”</li></ul><h3>Staging</h3><pre>{<br>  &quot;apiBaseUrl&quot;: &quot;https://staging-api.example.com&quot;,<br>  &quot;environment&quot;: &quot;staging&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;<br>}</pre><ul><li>Full API URL for staging server</li><li>Environment badge shows “staging”</li></ul><h3>Production</h3><pre>{<br>  &quot;apiBaseUrl&quot;: &quot;https://api.example.com&quot;,<br>  &quot;environment&quot;: &quot;production&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;<br>}</pre><ul><li>Full API URL for production</li><li>No environment badge (production is hidden)</li></ul><h3>Best Practices</h3><h3>1. Configuration Loading</h3><ul><li>Always provide default values for fallback</li><li>Handle errors gracefully</li><li>Log configuration loading for debugging</li><li>Validate critical configuration values</li></ul><h3>2. APP_INITIALIZER</h3><ul><li>Keep initializers fast and focused</li><li>Use promises for async operations</li><li>Don’t block unnecessarily</li><li>Handle errors appropriately</li></ul><h3>3. Configuration File</h3><ul><li>Store in public folder for easy access</li><li>Use JSON format for simplicity</li><li>Document all configuration properties</li><li>Version control the example file</li></ul><h3>4. Footer Badges</h3><ul><li>Only show environment in non-production</li><li>Keep badges small and unobtrusive</li><li>Use consistent styling</li><li>Update version on releases</li></ul><h3>Testing the Implementation</h3><ol><li><strong>Start the Application</strong>: npm start or docker-compose up</li><li><strong>Check Config Loading</strong>: Open browser console, should see “Application configuration loaded”</li><li><strong>Verify API Calls</strong>: API requests should use configured base URL</li><li><strong>Check Footer</strong>: Footer should show version badge and environment (if not production)</li><li><strong>Test Config Change</strong>: Update config.json and refresh (should pick up new values)</li></ol><h3>Common Issues and Solutions</h3><h3>Issue: Config not loading</h3><p><strong>Solution</strong>: Check that config.json exists in public/ folder and is accessible</p><h3>Issue: API calls failing after config change</h3><p><strong>Solution</strong>: Verify apiBaseUrl is correct and API server is accessible</p><h3>Issue: Footer badges not showing</h3><p><strong>Solution</strong>: Ensure ConfigService is injected and config is loaded</p><h3>Issue: Environment badge showing in production</h3><p><strong>Solution</strong>: Check that environment value is exactly “production” (case-insensitive check)</p><h3>Issue: APP_INITIALIZER not running</h3><p><strong>Solution</strong>: Verify initializer is registered in app.config.ts providers</p><h3>Project Structure</h3><p>After completing this setup:</p><pre>src/app/<br>├── core/<br>│   └── services/<br>│       └── config.service.ts<br>├── shared/<br>│   └── components/<br>│       └── footer/<br>│           ├── footer.ts<br>│           ├── footer.html<br>│           └── footer.scss<br>└── app.config.ts (updated)</pre><pre>public/<br>└── config.json</pre><h3>Conclusion</h3><p>We’ve successfully implemented:</p><ul><li>✅ Runtime configuration system with ConfigService</li><li>✅ APP_INITIALIZER to load config before app starts</li><li>✅ Dynamic API base path configuration</li><li>✅ Enhanced footer with environment and version badges</li><li>✅ Material Design chips for badge styling</li><li>✅ Conditional environment badge display</li><li>✅ Left-aligned footer layout</li><li>✅ Type-safe configuration interface</li></ul><p>The application now supports runtime configuration, allowing settings to be changed without rebuilding. The footer provides clear visibility into the current environment and version, helping with debugging and deployment verification.</p><p>In the next blog post, we’ll continue building out additional UI features and components.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, APP_INITIALIZER, Runtime Configuration, Configuration Service, HTTP Configuration Loading, Angular Material Chips, Footer Components, Environment Management, Version Display, Web Development, UI Development, Material Design</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1589fab6d5d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Building the User Menu in Header]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-building-the-user-menu-in-header-2ae57e9e2db5?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ae57e9e2db5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[angular-material]]></category>
            <category><![CDATA[angular-signals]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 02:00:59 GMT</pubDate>
            <atom:updated>2025-12-30T02:00:59.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEcBD7N2In5aDNFwdzRejg.png" /></figure><p><em>Creating a user menu with logout functionality and reactive authentication state management</em></p><h3>Introduction</h3><p>In our previous post, we implemented a comprehensive authentication service with token management, automatic refresh, and HTTP interceptors. Now we’ll enhance the user experience by adding a user menu to the header component. This menu will appear when users are logged in, providing easy access to logout functionality and preparing the foundation for future menu items like profile and settings.</p><h3>Why a User Menu?</h3><p>A user menu in the header provides several benefits:</p><ol><li><strong>User Experience</strong>: Quick access to account actions without navigating away</li><li><strong>Visual Feedback</strong>: Clear indication of authentication status</li><li><strong>Accessibility</strong>: Standard UI pattern users expect</li><li><strong>Extensibility</strong>: Easy to add more menu items (profile, settings, etc.)</li><li><strong>Professional Appearance</strong>: Polished, production-ready interface</li><li><strong>Reactive Updates</strong>: Menu appears/disappears automatically based on auth state</li></ol><h3>Architecture Overview</h3><p>Our user menu implementation consists of:</p><pre>User logs in<br>    ↓<br>Auth service emits login event<br>    ↓<br>Header component subscribes to login event<br>    ↓<br>Menu button appears (white circle with person icon)<br>    ↓<br>User clicks menu → Dropdown appears<br>    ↓<br>User clicks logout → Auth service logout() called<br>    ↓<br>Auth service emits logout event<br>    ↓<br>Menu button disappears</pre><h3>Step 1: Updating the Header Component</h3><p>We’ll enhance the header component to include authentication state management and the user menu:</p><p><strong>core/components/header/header.ts:</strong></p><pre>import { Component, OnInit, inject, signal } from &#39;@angular/core&#39;;<br>import { MatToolbarModule } from &#39;@angular/material/toolbar&#39;;<br>import { MatMenuModule } from &#39;@angular/material/menu&#39;;<br>import { MatIconModule } from &#39;@angular/material/icon&#39;;<br>import { MatButtonModule } from &#39;@angular/material/button&#39;;<br>import { takeUntil } from &#39;rxjs/operators&#39;;<br>import { AuthService } from &#39;../../../core/services/auth&#39;;<br>import { BaseComponent } from &#39;../../../core/base/base.component&#39;;<br>@Component({<br>  selector: &#39;app-header&#39;,<br>  imports: [<br>    MatToolbarModule,<br>    MatMenuModule,<br>    MatIconModule,<br>    MatButtonModule,<br>  ],<br>  templateUrl: &#39;./header.html&#39;,<br>  styleUrl: &#39;./header.scss&#39;,<br>})<br>export class Header extends BaseComponent implements OnInit {<br>  private authService = inject(AuthService);<br>  // Signal to track if user is logged in<br>  isLoggedIn = signal(false);<br>  ngOnInit(): void {<br>    // Check initial login state<br>    this.isLoggedIn.set(this.authService.isLoggedIn());<br>    // Subscribe to login events<br>    this.authService.onLogin$<br>      .pipe(takeUntil(this.destroyed$))<br>      .subscribe(() =&gt; {<br>        this.isLoggedIn.set(true);<br>      });<br>    // Subscribe to logout events<br>    this.authService.onLogout$<br>      .pipe(takeUntil(this.destroyed$))<br>      .subscribe(() =&gt; {<br>        this.isLoggedIn.set(false);<br>      });<br>  }<br>  /**<br>   * Handle logout action from menu<br>   */<br>  onLogout(): void {<br>    this.authService.logout();<br>  }<br>}</pre><h3>Key Features</h3><ol><li><strong>Extends BaseComponent</strong>: Automatic subscription cleanup</li><li><strong>Angular Signals</strong>: Reactive state with isLoggedIn signal</li><li><strong>Event Subscriptions</strong>: Listens to login/logout events from auth service</li><li><strong>Initial State Check</strong>: Checks authentication state on component initialization</li><li><strong>Logout Handler</strong>: Calls auth service logout method</li></ol><h3>Step 2: Creating the User Menu Template</h3><p>We’ll add the user menu to the header template with conditional rendering:</p><p><strong>core/components/header/header.html:</strong></p><pre>&lt;mat-toolbar color=&quot;primary&quot; class=&quot;header-toolbar&quot;&gt;<br>  &lt;div class=&quot;d-flex align-items-center justify-content-between w-100&quot;&gt;<br>    &lt;div class=&quot;d-flex align-items-center gap-3&quot;&gt;<br>      &lt;span class=&quot;logo-text&quot;&gt;Portal Starter Kit&lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;nav class=&quot;d-flex align-items-center gap-3&quot;&gt;<br>      @if (isLoggedIn()) {<br>        &lt;button<br>          mat-icon-button<br>          [matMenuTriggerFor]=&quot;userMenu&quot;<br>          aria-label=&quot;User menu&quot;<br>          class=&quot;user-menu-button&quot;&gt;<br>          &lt;mat-icon&gt;person&lt;/mat-icon&gt;<br>        &lt;/button&gt;<br>        &lt;mat-menu #userMenu=&quot;matMenu&quot; class=&quot;user-menu&quot;&gt;<br>          &lt;!-- Future menu items will be added here --&gt;<br>          &lt;button mat-menu-item (click)=&quot;onLogout()&quot;&gt;<br>            &lt;mat-icon&gt;logout&lt;/mat-icon&gt;<br>            &lt;span&gt;Logout&lt;/span&gt;<br>          &lt;/button&gt;<br>        &lt;/mat-menu&gt;<br>      }<br>    &lt;/nav&gt;<br>  &lt;/div&gt;<br>&lt;/mat-toolbar&gt;</pre><h3>Template Features</h3><ol><li><strong>Conditional Rendering</strong>: Uses @if to show menu only when logged in</li><li><strong>Material Menu</strong>: Uses matMenuTriggerFor to connect button to menu</li><li><strong>Accessibility</strong>: Includes aria-label for screen readers</li><li><strong>Icon Button</strong>: Material icon button with person icon</li><li><strong>Menu Items</strong>: Logout option with icon and text</li><li><strong>Extensible</strong>: Comment placeholder for future menu items</li></ol><h3>Step 3: Styling the User Menu Button</h3><p>We’ll create a distinctive white circular button that stands out on the blue header:</p><p><strong>core/components/header/header.scss:</strong></p><pre>.header-toolbar {<br>  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);<br>  background-color: var(--mat-sys-primary) !important;<br>  color: var(--mat-sys-on-primary) !important;<br>}<br>.logo-text {<br>  font-size: 1.25rem;<br>  font-weight: 500;<br>}<br>.user-menu-button {<br>  // White circular button<br>  width: 40px;<br>  height: 40px;<br>  border-radius: 50%;<br>  background-color: white;<br>  color: var(--mat-sys-primary);<br>  <br>  &amp;:hover {<br>    background-color: rgba(255, 255, 255, 0.9);<br>  }<br>  <br>  &amp;:focus {<br>    background-color: rgba(255, 255, 255, 0.9);<br>  }<br>  <br>  mat-icon {<br>    color: var(--mat-sys-primary);<br>  }<br>}<br>.user-menu {<br>  // Menu styling can be customized here if needed<br>}</pre><h3>Styling Features</h3><ol><li><strong>Circular Button</strong>: border-radius: 50% creates perfect circle</li><li><strong>White Background</strong>: Contrasts with blue header background</li><li><strong>Primary Color Icon</strong>: Icon uses primary color for visibility</li><li><strong>Hover Effects</strong>: Subtle transparency on hover</li><li><strong>Focus States</strong>: Accessible focus styling</li><li><strong>Fixed Size</strong>: 40px × 40px for consistent appearance</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djz8U9fvc2_CrqeFkAEpnw.png" /><figcaption>Our new user menu appears in the header in the top right when logged in</figcaption></figure><h3>Understanding the Reactive Flow</h3><p>The user menu reacts to authentication state changes:</p><pre>Component Initialization<br>    ↓<br>Check authService.isLoggedIn()<br>    ↓<br>Set isLoggedIn signal<br>    ↓<br>Template renders based on signal<br>    ↓<br>User logs in → onLogin$ emits<br>    ↓<br>Signal updates → Menu appears<br>    ↓<br>User logs out → onLogout$ emits<br>    ↓<br>Signal updates → Menu disappears</pre><h3>Why Signals?</h3><p>We use Angular Signals because:</p><ul><li><strong>Reactive</strong>: Automatically triggers change detection</li><li><strong>Zoneless Compatible</strong>: Works with Angular 21’s zoneless mode</li><li><strong>Simple API</strong>: Easy to read and update</li><li><strong>Performance</strong>: Efficient change detection</li></ul><h3>Angular Material Modules</h3><p>We use several Material modules:</p><ol><li><strong>MatMenuModule</strong>: Provides dropdown menu functionality</li><li><strong>MatIconModule</strong>: Material Design icons (person, logout)</li><li><strong>MatButtonModule</strong>: Icon button component</li><li><strong>MatToolbarModule</strong>: Header toolbar (already in use)</li></ol><h3>Best Practices</h3><h3>1. Subscription Management</h3><ul><li>Always use takeUntil(this.destroyed$) for subscriptions</li><li>Extend BaseComponent for automatic cleanup</li><li>Never forget to unsubscribe from observables</li></ul><h3>2. Conditional Rendering</h3><ul><li>Use @if for conditional template rendering</li><li>Check authentication state on initialization</li><li>Subscribe to auth events for reactive updates</li></ul><h3>3. Accessibility</h3><ul><li>Include aria-label for icon buttons</li><li>Provide text labels in menu items</li><li>Ensure keyboard navigation works</li><li>Test with screen readers</li></ul><h3>4. Styling</h3><ul><li>Use Material Design principles</li><li>Create visual contrast (white button on blue background)</li><li>Include hover and focus states</li><li>Use CSS variables for theming</li></ul><h3>5. Component Structure</h3><ul><li>Keep components focused and single-purpose</li><li>Separate concerns (header = layout, auth service = state)</li><li>Use dependency injection for services</li><li>Follow Angular style guide</li></ul><h3>Testing the Implementation</h3><ol><li><strong>Start the Application</strong>: npm start</li><li><strong>Login</strong>: Submit login form with valid credentials</li><li><strong>Verify Menu</strong>: Check that user menu button appears in header</li><li><strong>Test Menu</strong>: Click button to open dropdown menu</li><li><strong>Test Logout</strong>: Click logout option</li><li><strong>Verify Disappearance</strong>: Confirm menu button disappears after logout</li><li><strong>Test Refresh</strong>: Refresh page while logged in — menu should persist</li></ol><h3>Common Issues and Solutions</h3><h3>Issue: Menu doesn’t appear after login</h3><p><strong>Solution</strong>: Verify subscriptions are set up correctly and isLoggedIn signal is updating</p><h3>Issue: Menu appears when not logged in</h3><p><strong>Solution</strong>: Check initial state check in ngOnInit() and verify authService.isLoggedIn() returns correct value</p><h3>Issue: Menu doesn’t disappear after logout</h3><p><strong>Solution</strong>: Ensure logout event is being emitted and subscription is active</p><h3>Issue: Button styling doesn’t apply</h3><p><strong>Solution</strong>: Check CSS specificity and ensure styles are in component’s SCSS file</p><h3>Issue: Menu items not clickable</h3><p><strong>Solution</strong>: Verify (click) handlers are properly bound and menu is not being closed prematurely</p><h3>Extending the Menu</h3><p>The menu structure is designed for easy extension. To add more items:</p><pre>&lt;mat-menu #userMenu=&quot;matMenu&quot; class=&quot;user-menu&quot;&gt;<br>  &lt;button mat-menu-item (click)=&quot;onProfile()&quot;&gt;<br>    &lt;mat-icon&gt;account_circle&lt;/mat-icon&gt;<br>    &lt;span&gt;Profile&lt;/span&gt;<br>  &lt;/button&gt;<br>  &lt;button mat-menu-item (click)=&quot;onSettings()&quot;&gt;<br>    &lt;mat-icon&gt;settings&lt;/mat-icon&gt;<br>    &lt;span&gt;Settings&lt;/span&gt;<br>  &lt;/button&gt;<br>  &lt;mat-divider&gt;&lt;/mat-divider&gt;<br>  &lt;button mat-menu-item (click)=&quot;onLogout()&quot;&gt;<br>    &lt;mat-icon&gt;logout&lt;/mat-icon&gt;<br>    &lt;span&gt;Logout&lt;/span&gt;<br>  &lt;/button&gt;<br>&lt;/mat-menu&gt;</pre><p>You can add:</p><ul><li>Profile link</li><li>Settings link</li><li>Account management</li><li>Divider for visual separation</li><li>Any other user-related actions</li></ul><h3>Project Structure</h3><p>After completing this setup:</p><pre>src/app/<br>├── shared/<br>│   └── components/<br>│       └── header/<br>│           ├── header.ts<br>│           ├── header.html<br>│           └── header.scss<br>└── core/<br>    ├── services/<br>    │   └── auth.ts (provides login/logout events)<br>    └── base/<br>        └── base.component.ts (subscription cleanup)</pre><h3>Conclusion</h3><p>We’ve successfully implemented:</p><ul><li>✅ User menu in header component</li><li>✅ Conditional rendering based on authentication state</li><li>✅ Reactive updates using Angular Signals</li><li>✅ Event-driven state management</li><li>✅ Logout functionality</li><li>✅ White circular button styling</li><li>✅ Material Design menu component</li><li>✅ Extensible menu structure for future items</li></ul><p>The user menu provides a professional, accessible way for users to access account actions. The implementation is reactive, automatically showing and hiding based on authentication state, and provides a solid foundation for adding more menu items in the future.</p><p>In the next blog post, we’ll continue building out the user interface with additional features and components.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, Angular Material, User Menu, Header Components, Authentication UI, Material Design, Conditional Rendering, Component Communication, UI Development, Web Development, Angular Signals, Reactive Programming, User Interface Design</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ae57e9e2db5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Implementing UI Auth Services]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-implementing-ui-auth-services-e449e4c7e8e9?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/e449e4c7e8e9</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 01:59:29 GMT</pubDate>
            <atom:updated>2025-12-30T01:59:29.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFA0xOhL7mL299ZkqP8wUA.png" /></figure><p><em>Building a complete authentication system with token storage, automatic refresh, and HTTP interceptors</em></p><h3>Introduction</h3><p>In our previous post, we integrated OpenAPI Generator and connected our login component to the backend API. Now we’ll implement a comprehensive authentication service that manages JWT tokens, handles automatic token refresh, provides centralized login/logout events, and includes HTTP interceptors for seamless API authentication. This will create a production-ready authentication system that handles token lifecycle automatically.</p><h3>Why Token Management Matters</h3><p>Proper token management is crucial for security and user experience:</p><ol><li><strong>Security</strong>: Tokens stored securely in localStorage (or sessionStorage)</li><li><strong>Automatic Refresh</strong>: Seamless token renewal before expiration</li><li><strong>Centralized State</strong>: Single source of truth for authentication</li><li><strong>Event-Driven</strong>: Components can react to login/logout events</li><li><strong>HTTP Integration</strong>: Automatic token attachment to API requests</li><li><strong>Error Handling</strong>: Automatic logout on 401 errors</li></ol><h3>Architecture Overview</h3><p>Our authentication system consists of:</p><pre>User Login<br>    ↓<br>Store tokens in localStorage<br>    ↓<br>Set up automatic refresh timer<br>    ↓<br>Emit login event<br>    ↓<br>HTTP Interceptor adds token to requests<br>    ↓<br>Token expires → Auto-refresh 1 min before<br>    ↓<br>401 Error → Auto-logout</pre><h3>Step 1: Creating the Authentication Service</h3><p>We’ll replace our stubbed auth service with a comprehensive implementation:</p><p><strong>core/services/auth.ts:</strong></p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br>import { Subject, Observable, timer, EMPTY } from &#39;rxjs&#39;;<br>import { catchError, tap } from &#39;rxjs/operators&#39;;<br>import { AuthService as ApiAuthService } from &#39;../api/api/auth.service&#39;;<br>import { LoginResponseDto } from &#39;../api/model/login-response-dto&#39;;<br>import { RefreshTokenDto } from &#39;../api/model/refresh-token-dto&#39;;<br>import { TokenResponseDto } from &#39;../api/model/token-response-dto&#39;;<br>const STORAGE_KEYS = {<br>  ACCESS_TOKEN: &#39;auth_access_token&#39;,<br>  REFRESH_TOKEN: &#39;auth_refresh_token&#39;,<br>  EXPIRES_AT: &#39;auth_expires_at&#39;,<br>  USER: &#39;auth_user&#39;,<br>} as const;<br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class AuthService {<br>  private readonly apiAuthService: ApiAuthService;<br>  private readonly router: Router;<br>  // Event subjects for login/logout<br>  private readonly loginSubject = new Subject&lt;LoginResponseDto&gt;();<br>  private readonly logoutSubject = new Subject&lt;void&gt;();<br>  // Observable streams for login/logout events<br>  public readonly onLogin$: Observable&lt;LoginResponseDto&gt; = this.loginSubject.asObservable();<br>  public readonly onLogout$: Observable&lt;void&gt; = this.logoutSubject.asObservable();<br>  // Token refresh timer subscription<br>  private refreshTimerSubscription: any = null;<br>  private isRefreshing = false;<br>  constructor(<br>    apiAuthService: ApiAuthService,<br>    router: Router<br>  ) {<br>    this.apiAuthService = apiAuthService;<br>    this.router = router;<br>    // Initialize: restore tokens from localStorage and set up refresh timer<br>    this.initialize();<br>  }<br>  private initialize(): void {<br>    const accessToken = this.getAccessToken();<br>    const expiresAt = this.getExpiresAt();<br>    if (accessToken &amp;&amp; expiresAt) {<br>      const expirationDate = new Date(expiresAt);<br>      const now = new Date();<br>      if (expirationDate &gt; now) {<br>        // Token is still valid, set up refresh timer<br>        this.scheduleTokenRefresh(expirationDate);<br>      } else {<br>        // Token has expired, try to refresh it<br>        this.refreshToken();<br>      }<br>    }<br>  }<br>  isLoggedIn(): boolean {<br>    const accessToken = this.getAccessToken();<br>    const expiresAt = this.getExpiresAt();<br>    if (!accessToken || !expiresAt) {<br>      return false;<br>    }<br>    const expirationDate = new Date(expiresAt);<br>    const now = new Date();<br>    return expirationDate &gt; now;<br>  }<br>  getAccessToken(): string | null {<br>    return localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);<br>  }<br>  getRefreshToken(): string | null {<br>    return localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);<br>  }<br>  getExpiresAt(): string | null {<br>    return localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);<br>  }<br>  getUser(): any | null {<br>    const userStr = localStorage.getItem(STORAGE_KEYS.USER);<br>    if (userStr) {<br>      try {<br>        return JSON.parse(userStr);<br>      } catch {<br>        return null;<br>      }<br>    }<br>    return null;<br>  }<br>  handleLogin(loginResponse: LoginResponseDto): void {<br>    if (!loginResponse.accessToken || !loginResponse.refreshToken || !loginResponse.expiresAt) {<br>      console.error(&#39;Login response missing required token information&#39;);<br>      return;<br>    }<br>    // Store tokens in localStorage<br>    localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, loginResponse.accessToken);<br>    localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, loginResponse.refreshToken);<br>    localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, loginResponse.expiresAt);<br>    // Store user information if available<br>    if (loginResponse.user) {<br>      localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(loginResponse.user));<br>    }<br>    // Set up automatic token refresh<br>    const expirationDate = new Date(loginResponse.expiresAt);<br>    this.scheduleTokenRefresh(expirationDate);<br>    // Emit login event<br>    this.loginSubject.next(loginResponse);<br>  }<br>  logout(): void {<br>    // Clear tokens from localStorage<br>    localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);<br>    localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);<br>    localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);<br>    localStorage.removeItem(STORAGE_KEYS.USER);<br>    // Cancel refresh timer<br>    this.cancelTokenRefresh();<br>    // Emit logout event<br>    this.logoutSubject.next();<br>    // Navigate to login page<br>    this.router.navigate([&#39;/login&#39;]);<br>  }<br>  private scheduleTokenRefresh(expirationDate: Date): void {<br>    this.cancelTokenRefresh();<br>    const now = new Date();<br>    const timeUntilExpiration = expirationDate.getTime() - now.getTime();<br>    const oneMinute = 60 * 1000;<br>    // Calculate time until 1 minute before expiration<br>    const refreshTime = timeUntilExpiration - oneMinute;<br>    if (refreshTime &gt; 0) {<br>      // Schedule refresh 1 minute before expiration<br>      this.refreshTimerSubscription = timer(refreshTime).subscribe(() =&gt; {<br>        this.refreshToken();<br>      });<br>    } else if (timeUntilExpiration &gt; 0) {<br>      // Token expires in less than 1 minute, refresh immediately<br>      this.refreshToken();<br>    } else {<br>      // Token has already expired, try to refresh it<br>      this.refreshToken();<br>    }<br>  }<br>  private cancelTokenRefresh(): void {<br>    if (this.refreshTimerSubscription) {<br>      this.refreshTimerSubscription.unsubscribe();<br>      this.refreshTimerSubscription = null;<br>    }<br>  }<br>  refreshToken(): void {<br>    // Prevent multiple simultaneous refresh attempts<br>    if (this.isRefreshing) {<br>      console.log(&#39;Token refresh already in progress, skipping...&#39;);<br>      return;<br>    }<br>    const refreshToken = this.getRefreshToken();<br>    if (!refreshToken) {<br>      console.warn(&#39;No refresh token available, logging out&#39;);<br>      this.logout();<br>      return;<br>    }<br>    this.isRefreshing = true;<br>    const refreshTokenDto: RefreshTokenDto = {<br>      refreshToken: refreshToken,<br>    };<br>    this.apiAuthService<br>      .apiAuthRefreshPost(refreshTokenDto)<br>      .pipe(<br>        tap((response: TokenResponseDto) =&gt; {<br>          this.isRefreshing = false;<br>          <br>          if (response.accessToken &amp;&amp; response.refreshToken &amp;&amp; response.expiresAt) {<br>            // Update tokens in localStorage<br>            localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, response.accessToken);<br>            localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, response.refreshToken);<br>            localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, response.expiresAt);<br>            // Schedule next refresh<br>            const expirationDate = new Date(response.expiresAt);<br>            this.scheduleTokenRefresh(expirationDate);<br>            console.log(&#39;Token refreshed successfully&#39;);<br>          } else {<br>            console.error(&#39;Token refresh response missing required information&#39;);<br>            this.logout();<br>          }<br>        }),<br>        catchError((error) =&gt; {<br>          this.isRefreshing = false;<br>          console.error(&#39;Token refresh failed:&#39;, error);<br>          this.logout();<br>          return EMPTY;<br>        })<br>      )<br>      .subscribe();<br>  }<br>}</pre><h3>Key Features</h3><ol><li><strong>Token Storage</strong>: Stores access token, refresh token, expiration time, and user info in localStorage</li><li><strong>Automatic Initialization</strong>: Restores tokens on app startup and sets up refresh timer</li><li><strong>Event Streams</strong>: onLogin$ and onLogout$ observables for centralized state management</li><li><strong>Automatic Refresh</strong>: Schedules token refresh 1 minute before expiration</li><li><strong>Duplicate Prevention</strong>: Prevents multiple simultaneous refresh attempts</li><li><strong>Error Handling</strong>: Logs out on refresh failures</li></ol><h3>Step 2: Updating the Login Component</h3><p>We’ll update the login component to use the new handleLogin() method:</p><p><strong>features/auth/login/login.ts:</strong></p><pre>tap((response) =&gt; {<br>  // Handle successful login - store tokens and set up refresh timer<br>  this.authService.handleLogin(response);<br>  // Navigate to home/dashboard<br>  this.router.navigate([&#39;/&#39;]);<br>}),</pre><p>The login component now simply calls handleLogin() which handles all token storage and refresh setup automatically.</p><h3>Step 3: Creating the Auth HTTP Interceptor</h3><p>We’ll create an interceptor that automatically adds the Bearer token to all HTTP requests:</p><p><strong>core/interceptors/auth.interceptor.ts:</strong></p><pre>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { AuthService } from &#39;../services/auth&#39;;<br>export const authInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const authService = inject(AuthService);<br>  // Get the access token<br>  const accessToken = authService.getAccessToken();<br>  // Only add token if available and user is logged in<br>  if (accessToken &amp;&amp; authService.isLoggedIn()) {<br>    // Clone the request and add the Authorization header<br>    const clonedRequest = req.clone({<br>      setHeaders: {<br>        Authorization: `Bearer ${accessToken}`,<br>      },<br>    });<br>    return next(clonedRequest);<br>  }<br>  // If no token, proceed with the original request<br>  return next(req);<br>};</pre><p>This interceptor:</p><ul><li>Automatically adds Authorization: Bearer &lt;token&gt; to all HTTP requests</li><li>Only adds the token if the user is logged in and has a valid token</li><li>Works globally for all API calls</li></ul><h3>Step 4: Creating the Error HTTP Interceptor</h3><p>We’ll create an error interceptor that automatically logs out users on 401 errors:</p><p><strong>core/interceptors/error.interceptor.ts:</strong></p><pre>import { HttpInterceptorFn, HttpErrorResponse } from &#39;@angular/common/http&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { catchError, throwError } from &#39;rxjs&#39;;<br>import { AuthService } from &#39;../services/auth&#39;;<br>export const errorInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const authService = inject(AuthService);<br>  return next(req).pipe(<br>    catchError((error: HttpErrorResponse) =&gt; {<br>      // Handle 401 Unauthorized errors<br>      if (error.status === 401) {<br>        // Only log out if the user is currently logged in<br>        // This prevents logging out on login attempts with invalid credentials<br>        if (authService.isLoggedIn()) {<br>          console.warn(&#39;Received 401 Unauthorized response. User will be logged out.&#39;);<br>          authService.logout();<br>        }<br>      }<br>      // Re-throw the error so it can be handled by the calling code<br>      return throwError(() =&gt; error);<br>    })<br>  );<br>};</pre><p>This interceptor:</p><ul><li>Catches all HTTP errors</li><li>Automatically logs out on 401 errors (only if user is logged in)</li><li>Prevents logout on failed login attempts</li><li>Re-throws errors so components can still handle them</li></ul><h3>Step 5: Registering the Interceptors</h3><p>We’ll register both interceptors in the app configuration:</p><p><strong>app.config.ts:</strong></p><pre>import { provideHttpClient, withInterceptors } from &#39;@angular/common/http&#39;;<br>import { authInterceptor } from &#39;./core/interceptors/auth.interceptor&#39;;<br>import { errorInterceptor } from &#39;./core/interceptors/error.interceptor&#39;;<br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    // ... other providers<br>    provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])),<br>  ]<br>};</pre><p>The interceptors run in order:</p><ol><li><strong>Auth Interceptor</strong>: Adds token to requests</li><li><strong>Error Interceptor</strong>: Handles errors (including 401s)</li></ol><h3>Understanding Token Refresh Flow</h3><p>The automatic token refresh works as follows:</p><pre>Token expires in 60 minutes<br>    ↓<br>Timer scheduled for 59 minutes<br>    ↓<br>59 minutes later → refreshToken() called<br>    ↓<br>API call to /api/auth/refresh<br>    ↓<br>New tokens received<br>    ↓<br>Update localStorage<br>    ↓<br>Schedule next refresh (59 minutes from new expiration)</pre><h3>Why 1 Minute Before Expiration?</h3><p>Refreshing 1 minute before expiration:</p><ul><li>Provides buffer time for network delays</li><li>Prevents race conditions</li><li>Ensures seamless user experience</li><li>Handles slow API responses gracefully</li></ul><h3>Using Login/Logout Events</h3><p>Components can subscribe to authentication events:</p><pre>export class MyComponent extends BaseComponent implements OnInit {<br>  private authService = inject(AuthService);<br>  ngOnInit(): void {<br>    // Subscribe to login events<br>    this.authService.onLogin$<br>      .pipe(takeUntil(this.destroyed$))<br>      .subscribe((loginResponse) =&gt; {<br>        console.log(&#39;User logged in:&#39;, loginResponse.user);<br>        // Update UI, fetch user-specific data, etc.<br>      });<br>    // Subscribe to logout events<br>    this.authService.onLogout$<br>      .pipe(takeUntil(this.destroyed$))<br>      .subscribe(() =&gt; {<br>        console.log(&#39;User logged out&#39;);<br>        // Clear user-specific data, reset UI, etc.<br>      });<br>  }<br>}</pre><p>This enables:</p><ul><li>Centralized authentication state management</li><li>Automatic UI updates on login/logout</li><li>Clean separation of concerns</li><li>Event-driven architecture</li></ul><h3>localStorage vs sessionStorage</h3><p>We chose localStorage because:</p><ul><li><strong>Persistence</strong>: Tokens survive browser restarts</li><li><strong>User Experience</strong>: Users stay logged in across sessions</li><li><strong>Refresh Tokens</strong>: Long-lived refresh tokens work better with localStorage</li></ul><p><strong>Security Considerations</strong>:</p><ul><li>Tokens are still secure (HttpOnly cookies would be better, but localStorage is acceptable for SPAs)</li><li>XSS protection is still required</li><li>Tokens are cleared on logout</li><li>Automatic logout on 401 errors</li></ul><h3>Project Structure</h3><p>After completing this setup:</p><pre>src/app/<br>├── core/<br>│   ├── interceptors/<br>│   │   ├── auth.interceptor.ts<br>│   │   └── error.interceptor.ts<br>│   └── services/<br>│       └── auth.ts<br>├── features/<br>│   └── auth/<br>│       └── login/<br>│           └── login.ts (updated)<br>└── app.config.ts (updated)</pre><h3>Best Practices</h3><h3>1. Token Management</h3><ul><li>Always check token expiration before using</li><li>Store tokens securely (localStorage is acceptable for SPAs)</li><li>Clear tokens on logout</li><li>Handle refresh failures gracefully</li></ul><h3>2. HTTP Interceptors</h3><ul><li>Keep interceptors focused and single-purpose</li><li>Don’t modify request/response unnecessarily</li><li>Re-throw errors so components can handle them</li><li>Use functional interceptors (Angular 15+)</li></ul><h3>3. Error Handling</h3><ul><li>Only log out on 401 if user is actually logged in</li><li>Allow components to handle errors after interceptors</li><li>Provide user-friendly error messages</li><li>Log errors for debugging</li></ul><h3>4. Event-Driven Architecture</h3><ul><li>Use Subjects for user-triggered events</li><li>Expose observables for subscriptions</li><li>Clean up subscriptions properly</li><li>Keep event payloads minimal</li></ul><h3>Testing the Implementation</h3><ol><li><strong>Start the API</strong>: docker-compose up api</li><li><strong>Start the UI</strong>: npm start</li><li><strong>Test Login</strong>: Submit login form with valid credentials</li><li><strong>Verify Storage</strong>: Check localStorage for tokens</li><li><strong>Test Auto-Refresh</strong>: Wait for token refresh (or manually trigger)</li><li><strong>Test 401 Handling</strong>: Make an API call with invalid token</li><li><strong>Test Logout</strong>: Call authService.logout()</li></ol><h3>Common Issues and Solutions</h3><h3>Issue: Token refresh happens too frequently</h3><p><strong>Solution</strong>: Check that isRefreshing flag is working correctly</p><h3>Issue: 401 errors on login</h3><p><strong>Solution</strong>: Error interceptor checks isLoggedIn() to prevent logout on failed login</p><h3>Issue: Tokens not persisting</h3><p><strong>Solution</strong>: Verify localStorage is available (not in private/incognito mode)</p><h3>Issue: Interceptor not adding token</h3><p><strong>Solution</strong>: Check that interceptor is registered and isLoggedIn() returns true</p><h3>Conclusion</h3><p>We’ve successfully implemented:</p><ul><li>✅ Comprehensive authentication service with token management</li><li>✅ Automatic token refresh 1 minute before expiration</li><li>✅ Centralized login/logout events</li><li>✅ HTTP interceptor for automatic token attachment</li><li>✅ Error interceptor for automatic logout on 401 errors</li><li>✅ Token persistence in localStorage</li><li>✅ Seamless user experience with automatic token management</li></ul><p>The authentication system is now production-ready with automatic token management, error handling, and event-driven state management. Users can log in once and stay authenticated with automatic token refresh, and the system handles errors gracefully.</p><p>In the next blog post, we’ll add user profile management and additional authentication features.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, Authentication, Token Management, JWT, HTTP Interceptors, RxJS, Local Storage, Automatic Token Refresh, Error Handling, Security, Web Development, UI Development, State Management, Event-Driven Architecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e449e4c7e8e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Integrating OpenAPI Generator & Reactive Patterns]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-integrating-openapi-generator-reactive-patterns-508558283a7b?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/508558283a7b</guid>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[ui-development]]></category>
            <category><![CDATA[openapi-generator]]></category>
            <category><![CDATA[api-client]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 01:52:23 GMT</pubDate>
            <atom:updated>2025-12-30T02:56:51.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hK6GMHZwqP7DTsiw-iz3w.png" /></figure><p><em>Automatically generating type-safe API clients and implementing modern reactive patterns with Angular Signals</em></p><h3>Introduction</h3><p>In this blog post, we’ll integrate OpenAPI Generator to automatically generate a TypeScript API client from our backend’s Swagger specification. We’ll then connect our login component to the real API using reactive patterns with RxJS, implement proper error handling, and leverage Angular Signals for state management compatible with Angular 21’s zoneless change detection.</p><h3>Setting Up OpenAPI Generator</h3><h3>Installing the CLI Tool</h3><p>First, we’ll install the OpenAPI Generator CLI as a development dependency:</p><pre>npm install --save-dev @openapitools/openapi-generator-cli</pre><h3>Creating the Generation Script</h3><p>We’ll add an npm script to generate the API client:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;generate-api&quot;: &quot;openapi-generator-cli generate -g typescript-angular -i http://localhost:8080/swagger/v1/swagger.json -o ./src/app/core/api --additional-properties=ngVersion=21.0.0,providedInRoot=true,stringEnums=true,enumPropertyNaming=original,modelPropertyNaming=original,fileNaming=kebab-case,serviceSuffix=Service,withInterfaces=true,withSeparateModelsAndApi=true&quot;<br>  }<br>}</pre><p>This script:</p><ul><li>Uses the typescript-angular generator</li><li>Fetches the OpenAPI spec from our running API</li><li>Generates code compatible with Angular 21.0.0</li><li>Creates services as singletons (providedInRoot=true)</li><li>Uses kebab-case file naming</li><li>Separates models and API services for better organization</li></ul><h3>Generating the Client</h3><p>With the API running, we can generate the client:</p><pre>npm run generate-api</pre><p>This creates a complete TypeScript API client with:</p><ul><li><strong>Services</strong>: AuthService, UserService, DashboardService</li><li><strong>Models/DTOs</strong>: LoginDto, LoginResponseDto, UserDto, etc.</li><li><strong>Type-safe interfaces</strong>: Full IntelliSense support</li><li><strong>HTTP client integration</strong>: Ready to use with Angular’s HttpClient</li></ul><h3>Configuring the API Client</h3><h3>App Configuration</h3><p>We need to configure the API client in our app config:</p><pre>import { provideHttpClient, withInterceptorsFromDi } from &#39;@angular/common/http&#39;;<br>import { provideApi } from &#39;./core/api/provide-api&#39;;<br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideHttpClient(withInterceptorsFromDi()),<br>    provideApi({ basePath: &#39;&#39; }) // Empty string uses proxy in dev<br>  ]<br>};</pre><p>The basePath is set to an empty string so it uses our Angular proxy configuration in development, which forwards /api/* requests to <a href="http://localhost:8080.">http://localhost:8080.</a></p><h3>Implementing Reactive Patterns</h3><h3>Using Subjects for Form Submissions</h3><p>Instead of manually subscribing in the submit handler, we’ll use a reactive pattern with a Subject:</p><pre>private loginSubject = new Subject&lt;LoginDto&gt;();<br>ngOnInit(): void {<br>  this.loginSubject<br>    .pipe(<br>      takeUntil(this.destroyed$),<br>      tap(() =&gt; {<br>        this.isLoading.set(true);<br>        this.errorMessage.set(null);<br>      }),<br>      switchMap((loginDto) =&gt;<br>        this.apiAuthService.apiAuthLoginPost(loginDto).pipe(<br>          // Error handling inside switchMap<br>          catchError((error) =&gt; {<br>            // Handle errors<br>            return EMPTY;<br>          }),<br>          finalize(() =&gt; {<br>            this.isLoading.set(false);<br>          })<br>        )<br>      )<br>    )<br>    .subscribe();<br>}<br>onSubmit(): void {<br>  if (this.loginForm.valid) {<br>    const loginDto: LoginDto = {<br>      email: this.loginForm.value.email,<br>      password: this.loginForm.value.password,<br>    };<br>    this.loginSubject.next(loginDto);<br>  }<br>}</pre><p><strong>Benefits of this pattern:</strong></p><ul><li>No manual subscription in the submit handler</li><li>Automatic cleanup with takeUntil(this.destroyed$)</li><li>Centralized error handling</li><li>Clean separation of concerns</li></ul><h3>Error Handling with RxJS Operators</h3><p>We’ll use catchError and finalize for proper error handling:</p><pre>switchMap((loginDto) =&gt;<br>  this.apiAuthService.apiAuthLoginPost(loginDto).pipe(<br>    tap((response) =&gt; {<br>      // Handle success<br>      this.authService.setLoggedIn(true);<br>      this.router.navigate([&#39;/&#39;]);<br>    }),<br>    catchError((error) =&gt; {<br>      console.error(&#39;Login error:&#39;, error);<br>      <br>      // Handle different error types<br>      if (error.status === 401) {<br>        this.errorMessage.set(<br>          error.error?.message || <br>          error.error?.detail || <br>          &#39;Invalid email or password&#39;<br>        );<br>      } else if (error.status === 400) {<br>        this.errorMessage.set(<br>          error.error?.message || <br>          error.error?.detail || <br>          &#39;Invalid request. Please check your input.&#39;<br>        );<br>      } else if (error.status === 0) {<br>        this.errorMessage.set(<br>          &#39;Unable to connect to the server. Please check your connection.&#39;<br>        );<br>      } else {<br>        this.errorMessage.set(<br>          error.error?.message || <br>          error.error?.detail || <br>          &#39;An error occurred. Please try again.&#39;<br>        );<br>      }<br>      <br>      // Return EMPTY to continue the stream without erroring<br>      return EMPTY;<br>    }),<br>    finalize(() =&gt; {<br>      // Always runs, whether success or error<br>      this.isLoading.set(false);<br>    })<br>  )<br>)</pre><p><strong>Key points:</strong></p><ul><li>catchError handles errors and returns EMPTY to prevent stream errors</li><li>finalize always runs to reset loading state</li><li>Error messages are extracted from the API response</li><li>Different HTTP status codes are handled appropriately</li></ul><h3>Using Angular Signals for State</h3><h3>Why Signals?</h3><p>Angular 21 supports zoneless change detection, which means we need to use Signals for reactive state that triggers change detection automatically.</p><h3>Converting to Signals</h3><pre>import { signal } from &#39;@angular/core&#39;;<br>export class Login extends BaseComponent implements OnInit {<br>  isLoading = signal(false);<br>  errorMessage = signal&lt;string | null&gt;(null);<br>  <br>  // In the pipe:<br>  tap(() =&gt; {<br>    this.isLoading.set(true);<br>    this.errorMessage.set(null);<br>  })<br>}</pre><h3>Template Usage</h3><p>In the template, we call signals as functions:</p><pre>@if (errorMessage()) {<br>  &lt;div class=&quot;mb-3 p-3 bg-error-container text-on-error-container rounded&quot;&gt;<br>    {{ errorMessage() }}<br>  &lt;/div&gt;<br>}<br>&lt;button [disabled]=&quot;loginForm.invalid || isLoading()&quot;&gt;<br>  @if (isLoading()) {<br>    &lt;mat-spinner diameter=&quot;20&quot;&gt;&lt;/mat-spinner&gt;<br>    &lt;span&gt;Signing In...&lt;/span&gt;<br>  } @else {<br>    Sign In<br>  }<br>&lt;/button&gt;</pre><p><strong>Benefits:</strong></p><ul><li>Automatic change detection when signal values change</li><li>No need for ChangeDetectorRef.markForCheck()</li><li>More efficient — only components using the signal are checked</li><li>Compatible with zoneless change detection</li></ul><h3>BaseComponent for Subscription Management</h3><h3>Creating the Base Class</h3><p>To avoid memory leaks, we’ll create a base component that provides automatic subscription cleanup:</p><pre>import { Injectable, OnDestroy } from &#39;@angular/core&#39;;<br>import { Subject } from &#39;rxjs&#39;;<br>@Injectable()<br>export abstract class BaseComponent implements OnDestroy {<br>  protected readonly destroyed$ = new Subject&lt;void&gt;();<br>  ngOnDestroy(): void {<br>    this.destroyed$.next();<br>    this.destroyed$.complete();<br>  }<br>}</pre><h3>Using in Components</h3><p>Components extend BaseComponent and use takeUntil(this.destroyed$):</p><pre>export class Login extends BaseComponent implements OnInit {<br>  ngOnInit(): void {<br>    this.loginSubject<br>      .pipe(<br>        takeUntil(this.destroyed$), // Automatic cleanup<br>        // ... rest of the pipe<br>      )<br>      .subscribe();<br>  }<br>}</pre><p><strong>Benefits:</strong></p><ul><li>No need to manually implement ngOnDestroy in each component</li><li>Consistent pattern across all components</li><li>Prevents memory leaks automatically</li><li>Cleaner, more maintainable code</li></ul><h3>Complete Login Component</h3><p>Here’s the complete implementation:</p><pre>import { Component, inject, OnInit, signal } from &#39;@angular/core&#39;;<br>import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from &#39;@angular/forms&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br>import { Subject, EMPTY } from &#39;rxjs&#39;;<br>import { catchError, finalize, switchMap, takeUntil, tap } from &#39;rxjs/operators&#39;;<br>import { AuthService as ApiAuthService } from &#39;../../../core/api/api/auth.service&#39;;<br>import { LoginDto } from &#39;../../../core/api/model/login-dto&#39;;<br>import { AuthService } from &#39;../../../core/services/auth&#39;;<br>import { BaseComponent } from &#39;../../../core/base/base.component&#39;;<br><br>@Component({<br>  selector: &#39;app-login&#39;,<br>  // ... imports<br>})<br>export class Login extends BaseComponent implements OnInit {<br>  loginForm: FormGroup;<br>  isLoading = signal(false);<br>  errorMessage = signal&lt;string | null&gt;(null);<br>  private loginSubject = new Subject&lt;LoginDto&gt;();<br>  private apiAuthService = inject(ApiAuthService);<br>  private authService = inject(AuthService);<br>  private router = inject(Router);<br>  private fb = inject(FormBuilder);<br>  constructor() {<br>    super();<br>    this.loginForm = this.fb.group({<br>      email: [&#39;&#39;, [Validators.required, Validators.email]],<br>      password: [&#39;&#39;, [Validators.required, Validators.minLength(6)]],<br>    });<br>  }<br>  ngOnInit(): void {<br>    this.loginSubject<br>      .pipe(<br>        takeUntil(this.destroyed$),<br>        tap(() =&gt; {<br>          this.isLoading.set(true);<br>          this.errorMessage.set(null);<br>        }),<br>        switchMap((loginDto) =&gt;<br>          this.apiAuthService.apiAuthLoginPost(loginDto).pipe(<br>            tap((response) =&gt; {<br>              console.log(&#39;Login successful:&#39;, response);<br>              this.authService.setLoggedIn(true);<br>              this.router.navigate([&#39;/&#39;]);<br>            }),<br>            catchError((error) =&gt; {<br>              // Error handling...<br>              return EMPTY;<br>            }),<br>            finalize(() =&gt; {<br>              this.isLoading.set(false);<br>            })<br>          )<br>        )<br>      )<br>      .subscribe();<br>  }<br>  onSubmit(): void {<br>    if (this.loginForm.valid) {<br>      const loginDto: LoginDto = {<br>        email: this.loginForm.value.email,<br>        password: this.loginForm.value.password,<br>      };<br>      this.loginSubject.next(loginDto);<br>    }<br>  }<br>}</pre><h3>Best Practices</h3><h3>1. Error Handling</h3><ul><li>Always handle errors inside switchMap for HTTP calls</li><li>Return EMPTY from catchError to prevent stream errors</li><li>Use finalize for cleanup that must always run</li></ul><h3>2. State Management</h3><ul><li>Use Signals for component state in Angular 21+</li><li>Signals automatically trigger change detection</li><li>No need for manual change detection calls</li></ul><h3>3. Subscription Management</h3><ul><li>Use takeUntil(this.destroyed$) pattern</li><li>Extend BaseComponent for automatic cleanup</li><li>Never forget to unsubscribe from observables</li></ul><h3>4. Reactive Patterns</h3><ul><li>Use Subjects for user-triggered actions</li><li>Prefer RxJS operators over manual subscriptions</li><li>Keep side effects in tap operators</li></ul><h3>Testing the Integration</h3><ol><li><strong>Start the API</strong>: docker-compose up api</li><li><strong>Generate the client</strong>: npm run generate-api</li><li><strong>Start the UI</strong>: npm start</li><li><strong>Test login</strong>: Submit the form with valid/invalid credentials</li><li><strong>Verify</strong>: Check that loading states, errors, and navigation work correctly</li></ol><h3>Conclusion</h3><p>We’ve successfully:</p><ul><li>✅ Integrated OpenAPI Generator for automatic API client generation</li><li>✅ Configured the API client with proper base path</li><li>✅ Implemented reactive patterns with Subjects and RxJS operators</li><li>✅ Used Angular Signals for state management</li><li>✅ Created BaseComponent for automatic subscription cleanup</li><li>✅ Implemented proper error handling with user-friendly messages</li><li>✅ Connected the login form to the real backend API</li></ul><p>The login component now works end-to-end with proper error handling, loading states, and automatic change detection. In the next blog post, we’ll implement JWT token storage and refresh token management.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, OpenAPI Generator, API Client Generation, RxJS, Reactive Programming, Angular Signals, HTTP Client, Error Handling, State Management, Web Development, UI Development, TypeScript, Swagger, OpenAPI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=508558283a7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Building the Login Component & Auth Guard]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-building-the-login-component-auth-guard-a2a656b6514c?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2a656b6514c</guid>
            <category><![CDATA[route-guards]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular-material]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 18:58:43 GMT</pubDate>
            <atom:updated>2025-12-29T02:22:21.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MN8yuifJuzCUgRZ6PEG2Iw.png" /></figure><p><em>Creating a secure authentication flow with route guards and lazy-loaded components</em></p><h3>Introduction</h3><p>In our previous post, we built the layout structure and utility classes. Now we’ll create the authentication system for our Angular application. We’ll build a login component with form validation, an authentication service to manage login state, and route guards to protect our routes. We’ll also implement lazy loading for better performance and code splitting.</p><h3>Why Route Guards?</h3><p>Route guards are essential for securing your application:</p><ol><li><strong>Protection</strong>: Prevent unauthorized access to protected routes</li><li><strong>User Experience</strong>: Automatically redirect unauthenticated users to login</li><li><strong>Security</strong>: Enforce authentication at the route level</li><li><strong>Flexibility</strong>: Can check authentication, roles, permissions, etc.</li><li><strong>Separation of Concerns</strong>: Authentication logic separate from components</li></ol><h3>Architecture Overview</h3><p>Our authentication system consists of:</p><pre>User visits protected route<br>    ↓<br>Auth Guard checks authentication<br>    ↓<br>If not authenticated → Redirect to /login<br>If authenticated → Allow access<br>    ↓<br>Login Component → Auth Service → (Future: API call)</pre><h3>Step 1: Creating the Authentication Service</h3><p>First, we’ll create an authentication service to manage login state:</p><pre>ng generate service core/services/auth --skip-tests</pre><p><strong>core/services/auth.ts:</strong></p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class AuthService {<br>  // Stubbed: Will be implemented later with actual authentication logic<br>  private _isLoggedIn = false;<br>  /**<br>   * Check if the user is currently logged in<br>   * @returns true if logged in, false otherwise<br>   */<br>  isLoggedIn(): boolean {<br>    // TODO: Implement actual authentication check<br>    // This will check for valid JWT token, refresh token, etc.<br>    return this._isLoggedIn;<br>  }<br>  /**<br>   * Set the logged in status (for testing/stubbing)<br>   * @param status The login status<br>   */<br>  setLoggedIn(status: boolean): void {<br>    this._isLoggedIn = status;<br>  }<br>}</pre><p>The service is stubbed for now but provides the interface we’ll need:</p><ul><li>isLoggedIn(): Check authentication status</li><li>setLoggedIn(): For testing/stubbing (will be replaced with actual login logic)</li></ul><p>Later, this will check for JWT tokens, validate refresh tokens, and manage session state.</p><h3>Step 2: Creating the Auth Guard</h3><p>Next, we’ll create a route guard to protect our routes:</p><pre>ng generate guard core/guards/auth --skip-tests</pre><p><strong>core/guards/auth-guard.ts:</strong></p><pre>import { inject } from &#39;@angular/core&#39;;<br>import { CanActivateFn, Router } from &#39;@angular/router&#39;;<br>import { AuthService } from &#39;../services/auth&#39;;<br>export const authGuard: CanActivateFn = (route, state) =&gt; {<br>  const authService = inject(AuthService);<br>  const router = inject(Router);<br>  if (authService.isLoggedIn()) {<br>    return true;<br>  }<br>  // Redirect to login if not authenticated<br>  router.navigate([&#39;/login&#39;]);<br>  return false;<br>};</pre><h3>How Guards Work</h3><p>Angular’s functional guards (introduced in Angular 15+) use the CanActivateFn type:</p><ul><li><strong>Return </strong><strong>true</strong>: Allow navigation to proceed</li><li><strong>Return </strong><strong>false</strong>: Block navigation</li><li><strong>Redirect</strong>: Use router to navigate elsewhere</li></ul><p>The guard:</p><ol><li>Injects AuthService and Router using inject()</li><li>Checks if user is logged in</li><li>Returns true if authenticated, redirects to login otherwise</li></ol><h3>Step 3: Building the Login Component</h3><p>Now we’ll create the login component with Angular Material:</p><pre>ng generate component features/auth/login --skip-tests</pre><p><strong>features/auth/login/login.ts:</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from &#39;@angular/forms&#39;;<br>import { MatButtonModule } from &#39;@angular/material/button&#39;;<br>import { MatCardModule } from &#39;@angular/material/card&#39;;<br>import { MatFormFieldModule } from &#39;@angular/material/form-field&#39;;<br>import { MatIconModule } from &#39;@angular/material/icon&#39;;<br>import { MatInputModule } from &#39;@angular/material/input&#39;;<br>@Component({<br>  selector: &#39;app-login&#39;,<br>  imports: [<br>    ReactiveFormsModule,<br>    MatCardModule,<br>    MatFormFieldModule,<br>    MatInputModule,<br>    MatButtonModule,<br>    MatIconModule,<br>  ],<br>  templateUrl: &#39;./login.html&#39;,<br>  styleUrl: &#39;./login.scss&#39;,<br>})<br>export class Login {<br>  loginForm: FormGroup;<br>  constructor(private fb: FormBuilder) {<br>    this.loginForm = this.fb.group({<br>      email: [&#39;&#39;, [Validators.required, Validators.email]],<br>      password: [&#39;&#39;, [Validators.required, Validators.minLength(6)]],<br>    });<br>  }<br>  onSubmit(): void {<br>    if (this.loginForm.valid) {<br>      // TODO: Implement actual login logic<br>      console.log(&#39;Login form submitted:&#39;, this.loginForm.value);<br>    } else {<br>      // Mark all fields as touched to show validation errors<br>      Object.keys(this.loginForm.controls).forEach(key =&gt; {<br>        this.loginForm.get(key)?.markAsTouched();<br>      });<br>    }<br>  }<br>}</pre><h3>Form Setup</h3><ul><li><strong>Reactive Forms</strong>: Using FormBuilder for type-safe form handling</li><li><strong>Validators</strong>: Email format, required fields, minimum password length</li><li><strong>Material Modules</strong>: Card, form fields, inputs, buttons, icons</li></ul><h3>Step 4: Creating the Login Form Template</h3><p><strong>features/auth/login/login.html:</strong></p><pre>&lt;div class=&quot;login-container d-flex align-items-center justify-content-center h-100 p-8&quot;&gt;<br>  &lt;mat-card class=&quot;login-card p-8 w-100&quot;&gt;<br>    &lt;mat-card-header class=&quot;d-flex flex-column align-items-center mb-4&quot;&gt;<br>      &lt;h1 class=&quot;mb-2&quot; style=&quot;font-size: 1.75rem; font-weight: 500; margin: 0;&quot;&gt;<br>        Welcome Back<br>      &lt;/h1&gt;<br>      &lt;p class=&quot;text-center mb-0&quot; style=&quot;color: var(--mat-sys-on-surface-variant); font-size: 0.875rem;&quot;&gt;<br>        Sign in to your account<br>      &lt;/p&gt;<br>    &lt;/mat-card-header&gt;<br>    &lt;mat-card-content&gt;<br>      &lt;form [formGroup]=&quot;loginForm&quot; (ngSubmit)=&quot;onSubmit()&quot; class=&quot;d-flex flex-column gap-4&quot;&gt;<br>        &lt;mat-form-field appearance=&quot;outline&quot; class=&quot;w-100&quot;&gt;<br>          &lt;mat-label&gt;Email&lt;/mat-label&gt;<br>          &lt;input matInput type=&quot;email&quot; formControlName=&quot;email&quot; placeholder=&quot;Enter your email&quot;&gt;<br>          &lt;mat-icon matPrefix&gt;email&lt;/mat-icon&gt;<br>          @if (loginForm.get(&#39;email&#39;)?.hasError(&#39;required&#39;) &amp;&amp; loginForm.get(&#39;email&#39;)?.touched) {<br>            &lt;mat-error&gt;Email is required&lt;/mat-error&gt;<br>          }<br>          @if (loginForm.get(&#39;email&#39;)?.hasError(&#39;email&#39;) &amp;&amp; loginForm.get(&#39;email&#39;)?.touched) {<br>            &lt;mat-error&gt;Please enter a valid email&lt;/mat-error&gt;<br>          }<br>        &lt;/mat-form-field&gt;<br>        &lt;mat-form-field appearance=&quot;outline&quot; class=&quot;w-100&quot;&gt;<br>          &lt;mat-label&gt;Password&lt;/mat-label&gt;<br>          &lt;input matInput type=&quot;password&quot; formControlName=&quot;password&quot; placeholder=&quot;Enter your password&quot;&gt;<br>          &lt;mat-icon matPrefix&gt;lock&lt;/mat-icon&gt;<br>          @if (loginForm.get(&#39;password&#39;)?.hasError(&#39;required&#39;) &amp;&amp; loginForm.get(&#39;password&#39;)?.touched) {<br>            &lt;mat-error&gt;Password is required&lt;/mat-error&gt;<br>          }<br>          @if (loginForm.get(&#39;password&#39;)?.hasError(&#39;minlength&#39;) &amp;&amp; loginForm.get(&#39;password&#39;)?.touched) {<br>            &lt;mat-error&gt;Password must be at least 6 characters&lt;/mat-error&gt;<br>          }<br>        &lt;/mat-form-field&gt;<br>        &lt;button mat-raised-button color=&quot;primary&quot; type=&quot;submit&quot; class=&quot;w-100&quot; [disabled]=&quot;loginForm.invalid&quot;&gt;<br>          Sign In<br>        &lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/mat-card-content&gt;<br>  &lt;/mat-card&gt;<br>&lt;/div&gt;<br></pre><h3>Key Features</h3><ol><li><strong>Centered Layout</strong>: Using flexbox utility classes (d-flex align-items-center justify-content-center)</li><li><strong>Material Card</strong>: Clean card container for the form</li><li><strong>Form Fields</strong>: Outline appearance with icons</li><li><strong>Validation Errors</strong>: Using Angular’s new control flow syntax (@if)</li><li><strong>Submit Button</strong>: Disabled when form is invalid</li></ol><h3>Angular Control Flow</h3><p>Angular 17+ introduced new control flow syntax:</p><ul><li>@if instead of *ngIf</li><li>@for instead of *ngFor</li><li>@switch instead of [ngSwitch]</li></ul><p>This provides better type checking and performance.</p><h3>Step 5: Styling the Login Component</h3><p><strong>features/auth/login/login.scss:</strong></p><pre>.login-container {<br>  min-height: 100%;<br>}<br>.login-card {<br>  width: 100%;<br>  max-width: 400px;<br>}</pre><p>We use minimal custom styles and rely on utility classes:</p><ul><li>Container uses flexbox utilities for centering</li><li>Card has max-width for responsive design</li><li>Padding and spacing handled by utility classes</li></ul><h3>Step 6: Creating the Home/Dashboard Component</h3><p>We’ll create a simple home component for the protected route:</p><pre>ng generate component features/home --skip-tests</pre><p><strong>features/home/home.ts:</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>@Component({<br>  selector: &#39;app-home&#39;,<br>  imports: [],<br>  templateUrl: &#39;./home.html&#39;,<br>  styleUrl: &#39;./home.scss&#39;,<br>})<br>export class Home {<br>}</pre><p><strong>features/home/home.html:</strong></p><pre>&lt;div class=&quot;d-flex flex-column gap-4 p-4&quot;&gt;<br>  &lt;h1&gt;Dashboard&lt;/h1&gt;<br>  &lt;p&gt;Welcome to your dashboard. This is a protected route that requires authentication.&lt;/p&gt;<br>&lt;/div&gt;</pre><p>This is a placeholder that will be expanded later with actual dashboard content.</p><h3>Step 7: Setting Up Routes with Lazy Loading</h3><p>Now we’ll configure routing with lazy loading:</p><p><strong>app.routes.ts:</strong></p><pre>import { Routes } from &#39;@angular/router&#39;;<br>import { authGuard } from &#39;./core/guards/auth-guard&#39;;<br>export const routes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    loadComponent: () =&gt; import(&#39;./features/home/home&#39;).then(m =&gt; m.Home),<br>    canActivate: [authGuard],<br>  },<br>  {<br>    path: &#39;login&#39;,<br>    loadComponent: () =&gt; import(&#39;./features/auth/login/login&#39;).then(m =&gt; m.Login),<br>  },<br>  {<br>    path: &#39;**&#39;,<br>    redirectTo: &#39;&#39;,<br>  },<br>];</pre><h3>Lazy Loading Benefits</h3><p>Using loadComponent for lazy loading provides:</p><ol><li><strong>Code Splitting</strong>: Each component loads in its own chunk</li><li><strong>Smaller Initial Bundle</strong>: Login and Home not in main bundle</li><li><strong>Better Performance</strong>: Faster initial load time</li><li><strong>On-Demand Loading</strong>: Components load when routes are accessed</li></ol><h3>Route Configuration</h3><ul><li><strong>/</strong>: Home component (protected by authGuard)</li><li><strong>/login</strong>: Login component (public)</li><li><strong>**</strong>: Catch-all redirects to home</li></ul><h3>Step 8: How It All Works Together</h3><h3>Flow for Unauthenticated User</h3><ol><li>User visits / (home route)</li><li>authGuard checks authService.isLoggedIn()</li><li>Returns false (user not logged in)</li><li>Guard redirects to /login</li><li>Login component loads (lazy loaded)</li><li>User sees login form</li></ol><h3>Flow for Authenticated User</h3><ol><li>User visits / (home route)</li><li>authGuard checks authService.isLoggedIn()</li><li>Returns true (user logged in)</li><li>Guard allows navigation</li><li>Home component loads (lazy loaded)</li><li>User sees dashboard</li></ol><h3>Testing the Guard</h3><p>You can test the guard by setting the login status:</p><pre>// In browser console or component<br>authService.setLoggedIn(true);  // Now can access protected routes<br>authService.setLoggedIn(false); // Redirected to login</pre><h3>Form Validation</h3><p>The login form includes comprehensive validation:</p><h3>Email Field</h3><ul><li><strong>Required</strong>: Must not be empty</li><li><strong>Email Format</strong>: Must be valid email address</li><li><strong>Error Messages</strong>: Shown when field is touched and invalid</li></ul><h3>Password Field</h3><ul><li><strong>Required</strong>: Must not be empty</li><li><strong>Min Length</strong>: Must be at least 6 characters</li><li><strong>Error Messages</strong>: Shown when field is touched and invalid</li></ul><h3>Submit Behavior</h3><ul><li>Button disabled when form is invalid</li><li>All fields marked as touched on submit attempt</li><li>Validation errors displayed immediately</li></ul><h3>Styling with Utility Classes</h3><p>The login form uses utility classes extensively:</p><pre>&lt;!-- Centered container --&gt;<br>&lt;div class=&quot;d-flex align-items-center justify-content-center h-100 p-8&quot;&gt;<br>&lt;!-- Card with padding --&gt;<br>&lt;mat-card class=&quot;login-card p-8 w-100&quot;&gt;<br>&lt;!-- Form with gap between fields --&gt;<br>&lt;form class=&quot;d-flex flex-column gap-4&quot;&gt;<br>&lt;!-- Full width fields --&gt;<br>&lt;mat-form-field class=&quot;w-100&quot;&gt;</pre><p>This approach:</p><ul><li>Keeps CSS minimal</li><li>Makes styling intent clear in HTML</li><li>Ensures consistency across the app</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Vbe_0id7cHhR9xbfUg_Dg.png" /><figcaption>Our new login screen so far</figcaption></figure><h3>Project Structure</h3><p>After completing this setup:</p><pre>src/app/<br>├── core/<br>│   ├── guards/<br>│   │   └── auth-guard.ts<br>│   └── services/<br>│       └── auth.ts<br>├── features/<br>│   ├── auth/<br>│   │   └── login/<br>│   │       ├── login.ts<br>│   │       ├── login.html<br>│   │       └── login.scss<br>│   └── home/<br>│       ├── home.ts<br>│       ├── home.html<br>│       └── home.scss<br>└── app.routes.ts</pre><h3>Key Takeaways</h3><ol><li><strong>Auth Service</strong>: Centralized authentication state management</li><li><strong>Route Guards</strong>: Protect routes with functional guards</li><li><strong>Lazy Loading</strong>: Better performance with code splitting</li><li><strong>Form Validation</strong>: Comprehensive validation with Material Design</li><li><strong>Utility Classes</strong>: Consistent styling with minimal CSS</li><li><strong>Control Flow</strong>: Modern Angular syntax for conditionals</li></ol><h3>Next Steps</h3><p>With the login form and auth guard in place, we can now:</p><ol><li><strong>Implement API Integration</strong>: Connect login form to backend API</li><li><strong>JWT Token Management</strong>: Store and validate JWT tokens</li><li><strong>Token Refresh</strong>: Implement refresh token logic</li><li><strong>Error Handling</strong>: Handle login errors gracefully</li><li><strong>Loading States</strong>: Show loading indicators during authentication</li><li><strong>Remember Me</strong>: Add “remember me” functionality</li><li><strong>Password Reset</strong>: Link to password reset flow</li><li><strong>Registration</strong>: Create registration component</li></ol><h3>Conclusion</h3><p>We’ve built a solid foundation for authentication:</p><ul><li>✅ Login component with Material Design</li><li>✅ Form validation and error handling</li><li>✅ Auth service for state management</li><li>✅ Route guard for protection</li><li>✅ Lazy loading for performance</li><li>✅ Clean, maintainable code structure</li></ul><p>The authentication system is ready for API integration. In the next post, we’ll connect the login form to our .NET Core API backend and implement JWT token management.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, Angular Material, Authentication, Route Guards, Lazy Loading, Form Validation, Security, Web Development, UI Development</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2a656b6514c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Web Portal Starter Kit: Building the Layout Component & Utility Classes]]></title>
            <link>https://putnamtechnology.medium.com/custom-web-portal-starter-kit-building-the-layout-component-utility-classes-ef59fba41a97?source=rss-8cf4f35bd929------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef59fba41a97</guid>
            <category><![CDATA[flexbox]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[angular-material]]></category>
            <dc:creator><![CDATA[Chris Putnam]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 01:21:45 GMT</pubDate>
            <atom:updated>2025-12-28T01:21:45.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__jxmCPM6TBqe_rErbUNrA.png" /></figure><p><em>Creating a reusable layout structure and comprehensive utility classes for consistent styling</em></p><h3>Introduction</h3><p>In our previous post, we scaffolded the Angular UI and got the basic application running. Now we’ll build a proper layout structure with header and footer components, and create a comprehensive set of utility classes similar to Bootstrap. This will give us a solid foundation for building out the rest of our application with consistent styling and reusable components.</p><h3>Why a Layout Component?</h3><p>A layout component provides several benefits:</p><ol><li><strong>Consistency</strong>: Ensures all pages have the same header and footer</li><li><strong>Maintainability</strong>: Update header/footer in one place, affects entire app</li><li><strong>Separation of Concerns</strong>: Layout logic separate from page content</li><li><strong>Reusability</strong>: Header and footer can be used across different layouts</li><li><strong>Better UX</strong>: Consistent navigation and branding throughout the app</li></ol><h3>Why Utility Classes?</h3><p>Utility classes (like Bootstrap’s) offer:</p><ol><li><strong>Rapid Development</strong>: Style elements quickly without writing custom CSS</li><li><strong>Consistency</strong>: Standardized spacing, alignment, and layout values</li><li><strong>Maintainability</strong>: Change spacing scale in one place</li><li><strong>Readability</strong>: HTML shows styling intent clearly</li><li><strong>Flexibility</strong>: Combine classes for complex layouts without custom CSS</li></ol><h3>Step 1: Creating the Component Structure</h3><p>We’ll create a layout component with header and footer as separate components:</p><pre>ng generate component shared/layout --skip-tests<br>ng generate component shared/components/header --skip-tests<br>ng generate component shared/components/footer --skip-tests</pre><p>This creates a clean structure:</p><pre>src/app/shared/<br>├── layout/<br>│   ├── layout.ts<br>│   ├── layout.html<br>│   └── layout.scss<br>└── components/<br>    ├── header/<br>    │   ├── header.ts<br>    │   ├── header.html<br>    │   └── header.scss<br>    └── footer/<br>        ├── footer.ts<br>        ├── footer.html<br>        └── footer.scss</pre><h3>Step 2: Building the Utility Classes</h3><p>First, let’s create a comprehensive utility classes file. We’ll create src/styles/utilities.scss with flexbox, margin, padding, and other utilities similar to Bootstrap.</p><h3>Flexbox Utilities</h3><pre>// Display<br>.d-flex { display: flex; }<br>.d-inline-flex { display: inline-flex; }<br>.d-block { display: block; }<br>.d-none { display: none; }<br>// Flex Direction<br>.flex-row { flex-direction: row; }<br>.flex-column { flex-direction: column; }<br>// Justify Content<br>.justify-content-start { justify-content: flex-start; }<br>.justify-content-center { justify-content: center; }<br>.justify-content-between { justify-content: space-between; }<br>.justify-content-end { justify-content: flex-end; }<br>// Align Items<br>.align-items-start { align-items: flex-start; }<br>.align-items-center { align-items: center; }<br>.align-items-end { align-items: flex-end; }<br>// Flex Grow/Shrink<br>.flex-grow-1 { flex-grow: 1; }<br>.flex-shrink-0 { flex-shrink: 0; }</pre><h3>Margin &amp; Padding Utilities</h3><p>We create a scale from 0 to 12 (using rem units):</p><pre>// Margin scale: 0, 1 (0.25rem), 2 (0.5rem), 3 (0.75rem), 4 (1rem), etc.<br>.m-0 { margin: 0; }<br>.m-1 { margin: 0.25rem; }<br>.m-2 { margin: 0.5rem; }<br>.m-4 { margin: 1rem; }<br>// ... up to m-12<br>// Individual sides<br>.mt-4 { margin-top: 1rem; }<br>.mb-4 { margin-bottom: 1rem; }<br>.ms-4 { margin-inline-start: 1rem; }<br>.me-4 { margin-inline-end: 1rem; }<br>// Combined<br>.mx-4 { margin-left: 1rem; margin-right: 1rem; }<br>.my-4 { margin-top: 1rem; margin-bottom: 1rem; }<br>// Same pattern for padding: .p-*, .pt-*, .pb-*, .px-*, .py-*</pre><h3>Other Utilities</h3><pre>// Width &amp; Height<br>.w-100 { width: 100%; }<br>.w-50 { width: 50%; }<br>.h-100 { height: 100%; }<br>// Overflow<br>.overflow-auto { overflow: auto; }<br>.overflow-y-auto { overflow-y: auto; }<br>// Text Alignment<br>.text-center { text-align: center; }<br>.text-start { text-align: start; }<br>.text-end { text-align: end; }</pre><h3>Importing Utilities</h3><p>In src/styles.scss, we import the utilities:</p><pre>@use &#39;@angular/material&#39; as mat;<br>@use &#39;./styles/utilities.scss&#39;;<br>html {<br>  @include mat.theme((...));<br>}</pre><p><strong>Important</strong>: In SCSS, @use rules must come before @import rules. We use @use for the utilities file to follow modern Sass best practices.</p><h3>Step 3: Building the Layout Component</h3><p>The layout component uses flexbox to create a full-height structure:</p><p><strong>layout.html:</strong></p><pre>&lt;div class=&quot;d-flex flex-column flex-grow-1&quot;&gt;<br>  &lt;app-header&gt;&lt;/app-header&gt;<br>  &lt;main class=&quot;flex-grow-1 overflow-y-auto&quot;&gt;<br>    &lt;router-outlet /&gt;<br>  &lt;/main&gt;<br>  &lt;app-footer&gt;&lt;/app-footer&gt;<br>&lt;/div&gt;</pre><p><strong>layout.ts:</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { RouterOutlet } from &#39;@angular/router&#39;;<br>import { Header } from &#39;../components/header/header&#39;;<br>import { Footer } from &#39;../components/footer/footer&#39;;<br>@Component({<br>  selector: &#39;app-layout&#39;,<br>  imports: [RouterOutlet, Header, Footer],<br>  templateUrl: &#39;./layout.html&#39;,<br>  styleUrl: &#39;./layout.scss&#39;,<br>})<br>export class Layout {<br>}</pre><p><strong>layout.scss:</strong></p><pre>// Layout component uses utility classes only<br>// All styling is handled by utilities.scss</pre><p>Notice we use <strong>zero custom styles</strong> in the layout component — everything is handled by utility classes!</p><h3>Step 4: Full-Height Layout with Flexbox</h3><p>To make the layout fill the full viewport height, we set up a flexbox chain:</p><p><strong>styles.scss:</strong></p><pre>html {<br>  height: 100%;<br>}<br>body {<br>  height: 100%;<br>  margin: 0;<br>}<br>app-root {<br>  display: flex;<br>  flex-direction: column;<br>  height: 100%;<br>  width: 100%;<br>}</pre><p>The layout structure:</p><ul><li>html → height: 100% (viewport height)</li><li>body → height: 100%</li><li>app-root → height: 100% + flex container</li><li>Layout container → flex-grow-1 (fills app-root)</li><li>Main content → flex-grow-1 (fills space between header/footer)</li></ul><p>This approach avoids min-height: 100vh and uses pure flexbox for a more reliable layout.</p><h3>Step 5: Building the Header Component</h3><p>The header uses Angular Material’s toolbar with Material Design 3 styling:</p><p><strong>header.html:</strong></p><pre>&lt;mat-toolbar class=&quot;header-toolbar&quot;&gt;<br>  &lt;div class=&quot;d-flex align-items-center justify-content-between w-100 px-4&quot;&gt;<br>    &lt;div class=&quot;d-flex align-items-center gap-3&quot;&gt;<br>      &lt;span class=&quot;logo-text&quot;&gt;Portal Starter Kit&lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;nav class=&quot;d-flex align-items-center gap-3&quot;&gt;<br>      &lt;!-- Navigation items will be added here --&gt;<br>    &lt;/nav&gt;<br>  &lt;/div&gt;<br>&lt;/mat-toolbar&gt;</pre><p><strong>header.ts:</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { MatToolbarModule } from &#39;@angular/material/toolbar&#39;;<br>@Component({<br>  selector: &#39;app-header&#39;,<br>  imports: [MatToolbarModule],<br>  templateUrl: &#39;./header.html&#39;,<br>  styleUrl: &#39;./header.scss&#39;,<br>})<br>export class Header {<br>}</pre><p><strong>header.scss:</strong></p><pre>.header-toolbar {<br>  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);<br>  // Apply primary color background using Material 3 CSS variables<br>  background-color: var(--mat-sys-primary) !important;<br>  color: var(--mat-sys-on-primary) !important;<br>}<br>.logo-text {<br>  font-size: 1.25rem;<br>  font-weight: 500;<br>}</pre><h3>Material Design 3 Color Attribute Issue</h3><p>In Angular Material 21 (Material Design 3), the color=&quot;primary&quot; attribute on mat-toolbar no longer automatically applies the background color. Instead, we use Material 3 CSS variables:</p><ul><li>var(--mat-sys-primary) - Primary color</li><li>var(--mat-sys-on-primary) - Text color on primary background</li></ul><p>This is the recommended approach for Material Design 3.</p><h3>Step 6: Building the Footer Component</h3><p>The footer is simple and uses utility classes:</p><p><strong>footer.html:</strong></p><pre>&lt;footer class=&quot;footer-container&quot;&gt;<br>  &lt;div class=&quot;d-flex align-items-center justify-content-center py-4 px-4&quot;&gt;<br>    &lt;p class=&quot;mb-0 text-center&quot;&gt;<br>      &amp;copy; {{ currentYear }} Portal Starter Kit. All rights reserved.<br>    &lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/footer&gt;</pre><p><strong>footer.ts:</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>@Component({<br>  selector: &#39;app-footer&#39;,<br>  imports: [],<br>  templateUrl: &#39;./footer.html&#39;,<br>  styleUrl: &#39;./footer.scss&#39;,<br>})<br>export class Footer {<br>  currentYear = new Date().getFullYear();<br>}</pre><p><strong>footer.scss:</strong></p><pre>.footer-container {<br>  background-color: var(--mat-sys-surface-variant);<br>  color: var(--mat-sys-on-surface-variant);<br>  border-top: 1px solid var(--mat-sys-outline-variant);<br>  margin-top: auto;<br>}</pre><p>The footer uses Material Design 3 CSS variables for theming and automatically displays the current year.</p><h3>Step 7: Updating the App Component</h3><p>Finally, we update the main app component to use the layout:</p><p><strong>app.html:</strong></p><pre>&lt;app-layout&gt;&lt;/app-layout&gt;</pre><p><strong>app.ts:</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Layout } from &#39;./shared/layout/layout&#39;;<br>@Component({<br>  selector: &#39;app-root&#39;,<br>  imports: [Layout],<br>  templateUrl: &#39;./app.html&#39;,<br>  styleUrl: &#39;./app.scss&#39;<br>})<br>export class App {<br>  title = &#39;Portal Starter Kit&#39;;<br>}</pre><h3>Using Utility Classes</h3><p>Now you can use utility classes throughout your application:</p><pre>&lt;!-- Flexbox layout --&gt;<br>&lt;div class=&quot;d-flex justify-content-between align-items-center px-4 py-2&quot;&gt;<br>  &lt;h1 class=&quot;mb-0&quot;&gt;Title&lt;/h1&gt;<br>  &lt;button class=&quot;ms-3&quot;&gt;Action&lt;/button&gt;<br>&lt;/div&gt;<br>&lt;!-- Spacing --&gt;<br>&lt;div class=&quot;container my-4&quot;&gt;<br>  &lt;p class=&quot;mb-3&quot;&gt;Content with margin bottom&lt;/p&gt;<br>  &lt;div class=&quot;p-4&quot;&gt;Content with padding&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;!-- Responsive layout --&gt;<br>&lt;div class=&quot;d-flex flex-column gap-4&quot;&gt;<br>  &lt;div class=&quot;w-100&quot;&gt;Full width&lt;/div&gt;<br>  &lt;div class=&quot;w-50 mx-auto&quot;&gt;Centered half width&lt;/div&gt;<br>&lt;/div&gt;</pre><h3>Key Takeaways</h3><ol><li><strong>Layout Component</strong>: Provides consistent structure across all pages</li><li><strong>Utility Classes</strong>: Enable rapid development with consistent styling</li><li><strong>Flexbox Layout</strong>: Full-height layout without min-height: 100vh</li><li><strong>Material Design 3</strong>: Use CSS variables for theming</li><li><strong>Minimal Custom CSS</strong>: Prefer utility classes over custom styles</li><li><strong>Component Separation</strong>: Header and footer as separate, reusable components</li></ol><h3>Project Structure</h3><p>After completing this setup:</p><pre>src/app/<br>├── app.ts<br>├── app.html<br>├── shared/<br>│   ├── layout/<br>│   │   ├── layout.ts<br>│   │   ├── layout.html<br>│   │   └── layout.scss<br>│   └── components/<br>│       ├── header/<br>│       └── footer/<br>src/styles/<br>├── utilities.scss<br>└── styles.scss</pre><h3>Next Steps</h3><p>With the layout and utility classes in place, we can now:</p><ol><li><strong>Build Authentication UI</strong>: Login, registration, password reset forms</li><li><strong>Create Dashboard</strong>: User dashboard with Material components</li><li><strong>Implement Services</strong>: HTTP services for API communication</li><li><strong>Add Routing</strong>: Protected routes with authentication guards</li><li><strong>Build Forms</strong>: Use utility classes for consistent form layouts</li></ol><h3>Conclusion</h3><p>We’ve created a solid foundation for our Angular application with:</p><ul><li>A reusable layout component structure</li><li>Comprehensive utility classes for rapid development</li><li>Full-height flexbox layout</li><li>Material Design 3 integration</li><li>Clean, maintainable component architecture</li></ul><p>The layout is ready, and utility classes are available throughout the application. This foundation will make building the rest of the UI much faster and more consistent.</p><p><strong>Tags</strong>: Angular, TypeScript, Frontend Development, Angular Material, Layout Components, Utility Classes, Flexbox, SCSS, Web Development, UI Development, Component Architecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef59fba41a97" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>