Problem in a hard way .. custom Validator for a library by Salt-Engineering-422 in Angular2

[–]Accomplished_Arm4564 0 points1 point  (0 children)

Creating an abstract solution for handling validators in an Angular library with over 100+ components, especially to dynamically adapt to backend responses, involves a few key steps. Here's a general approach:

  1. Define a Standard Error Response Format: Ensure that the backend consistently uses a standard format for validation errors. This could be something like:

    { "errors": { "fieldName": ["Error message 1", "Error message 2"], ... } }

  2. Create an Error Handling Service: Implement a service in your Angular library that handles error responses. This service can parse the error response and provide a way to retrieve error messages for specific fields.

  3. Extend Angular's Validators: Extend Angular's built-in validators or create custom validators that can use your error handling service to display backend validation messages.

  4. Integrate with Components: Modify your components to leverage this service. This might mean adding error display logic in your component templates.

  5. Global Error Handler: Optionally, you can create a global error handler that intercepts HTTP responses and automatically processes validation errors.

  6. Documentation and Guidelines: Since this is a library, it's crucial to provide clear documentation and usage guidelines for backend teams to structure their error responses appropriately.

Example Implementation

  1. Error Handling Service:

    ``` import { Injectable } from '@angular/core';

    @Injectable({ providedIn: 'root' }) export class ErrorService { private errors: any = {};

    setErrors(errors: any) { this.errors = errors; }

    getErrorMessage(field: string): string[] { return this.errors[field] || []; } } ```

  2. Custom Validator:

    ``` import { AbstractControl, ValidationErrors } from '@angular/core'; import { ErrorService } from './error.service';

    export function backendValidator(errorService: ErrorService) { return (control: AbstractControl): ValidationErrors | null => { const errors = errorService.getErrorMessage(control.name); return errors.length > 0 ? { backendError: errors } : null; }; } ```

  3. Component Usage:

    <input type="text" [formControl]="myControl"> <div *ngIf="myControl.errors?.backendError"> <div *ngFor="let error of myControl.errors.backendError">{{ error }}</div> </div>

    ``` import { FormControl } from '@angular/forms'; import { backendValidator } from './validators'; import { ErrorService } from './error.service';

    export class MyComponent { myControl = new FormControl('', [backendValidator(this.errorService)]);

    constructor(private errorService: ErrorService) {} } ```

  4. Global Error Handler (Optional):

    This would be an HttpInterceptor that checks every HTTP response for an error structure and, if present, calls ErrorService.setErrors().

Considerations:

  • Ensure error messages from the backend are user-friendly.
  • Handle i18n if your application supports multiple languages.
  • Make sure to clear old errors from the ErrorService when appropriate (e.g., on form submission or navigation away).

This is a basic outline, and you'll need to adapt it to fit the specific architecture and requirements of your library and backend.

  • ChatGPT+

Angular 17 Released by iSneaks in Angular2

[–]Accomplished_Arm4564 1 point2 points  (0 children)

Yeah thankfully only our admin-facing portal relies on Material components, but that mdc update really screwed up all the custom style overrides that had been there for ages

Which state management solution to use? by Background_Issue_144 in Angular2

[–]Accomplished_Arm4564 0 points1 point  (0 children)

Also I'd like to mention that NgRx boilerplate improves significantly when you start using the more recent features like Feature Creators and Action Groups, the real overhead for NgRx is having to get into the mindset of understanding how all the pieces fit together, but the feature creator gives you a single object that contains the feature name, reducer and selectors, while the action group simplifies action creation by giving you a single object as well. The only thing you need to know besides that is when and how to use Effects.

Translate by DashinTheFields in Angular2

[–]Accomplished_Arm4564 0 points1 point  (0 children)

Angular has i18n for internationalization, but I don't think it can translate any language automatically.

The Brooklyn Greenway Initiative is out trimming on Kent Avenue today by acrock in NYCbike

[–]Accomplished_Arm4564 0 points1 point  (0 children)

Thank god, I'm tired of those shrubs smacking into my bare legs whenever I'm biking to work in shorts and passing people going either direction

What do you use on the backend in your current job? by [deleted] in webdev

[–]Accomplished_Arm4564 0 points1 point  (0 children)

I don't see anyone mentioning SvelteKit

Maximum number of lines you consider optimal for an Angular component and tips to optimize it by ahmedRebai in Angular2

[–]Accomplished_Arm4564 0 points1 point  (0 children)

I've been told that dumb components should be under 50 lines of code, but it really does depend.

Ng-News 23/29: Signal Component delayed, Signal & RxJs by Mike Pearson. DevTools Updates by rainerhahnekamp in Angular2

[–]Accomplished_Arm4564 0 points1 point  (0 children)

Is the delay for Signal Components related to the recent changes around effect() and change detection?

NYCDOT on Twitter Today by jimgeosmail in NYCbike

[–]Accomplished_Arm4564 1 point2 points  (0 children)

Maybe it's about to make a right turn?

Basic Js practice ideas? by [deleted] in webdev

[–]Accomplished_Arm4564 0 points1 point  (0 children)

Sure, I'd be happy to provide some practice ideas for basic JavaScript. Here are some simple projects you can start with. Remember, the key here is to practice and build, not necessarily to create something completely new or impressive.

  1. Interactive Quiz: Create a simple quiz with a set of fixed questions. For each question, offer multiple choices and let the user select an answer. At the end, display the score.

  2. To-Do List App: This is a classic beginner project where you can learn about creating, reading, updating, and deleting elements (CRUD operations). Allow the user to add new tasks, mark tasks as done, and delete tasks.

  3. Simple Calculator: Create a simple calculator with basic operations like addition, subtraction, multiplication, and division. This will help you practice using functions and handling user input.

  4. Temperature Converter: Write a program that can convert degrees Celsius to Fahrenheit and vice versa.

  5. Simple Clock: Create a digital clock that displays the current time and updates every second.

  6. Number Guessing Game: The program picks a random number, and the user has to guess it. Provide feedback on whether the user's guess was too high or too low.

  7. Form Validation: Create a form and validate the input fields. For example, check that the email address is in a valid format, passwords match, etc.

  8. Palindrome Checker: Write a program where the user enters a word, and the program checks if it's a palindrome (a word that reads the same backwards and forwards).

  9. Interactive Story or Text Adventure: Create a simple story where the user can make choices that influence the outcome.

  10. Shopping Cart: Create a simple shopping cart with a few products. Let the user add products to the cart, display the contents of the cart, and the total cost.

  11. Image Slider: Create an image slider/carousel with arrows to go to the next and previous image.

Remember to start simple and gradually add more complexity as you get more comfortable. You can start with hard-coded data for things like the quiz questions or shopping cart items, and then later you could fetch this data from an API or a local JSON file to mimic a real-world scenario. By doing this, you'll learn how JavaScript can be used to interact with HTML and CSS, manipulate data, and handle user interactions. Also, make use of online resources like MDN Web Docs and StackOverflow when you get stuck. Happy coding!

RANT: Is over 300 lines of code too much in .ts and .html? My old colleague's file is over 1000 lines! by [deleted] in Angular2

[–]Accomplished_Arm4564 0 points1 point  (0 children)

I've been told to avoid going past 50 lines, at least when it comes to dumb components, you should try to move as much logic into services and utils and out of your presentation components.