Search code examples
angularangular-reactive-forms

Add a class from array if propery matches name attribute in list element


I have a reactive form with multiple "blocks", like this: form

and on the left I have like a sidebar where every block number matches a number in the sidebar. If there are any errors, a class is added to each li element. The sidebar is basically just a unordered list (not from an array) and have a name attribute that also matches the name of the block :

    <ul>
     <li name="Personal information">1</li>
     <li name="Employment">2</li>
      //rest of the li elements
   </ul>

sidebar

The valdation is done from backend and I get an array with objects with the errors that look like this:

[
    {
        "Message": "Name is required",
        "Type": "Error",
        "Field": "Employment"
    },
    {
        "Message": "Date must start...",
        "Type": "Warning",
        "Field": "Personal Information",
    },

]

I'm struggeling how to add the classes for the sidebar without doing alot of if statements (there are 16 blocks in the form).

  • I have to check if the property Field in error array matches the name attribute in sidebar, then add class if it exists.
  • The class sholud be equal to the Type propery in error array.
  • If theres no errors for that name then add class valid.

Any ideas how to do this the best way?


Solution

  • Write a simple function to check for errors:

    getValidationType(errors, field) {
      return errors.find(error => error.field === field)?.Type ?? 'valid';
    }
    

    and then call it in the template:

    <li name="Personal information" [class]="getValidationType(errorArray, 'Personal information')">1</li>
    

    You could also create an array with all fields and iterate through it:

    fields = [
      'Personal information',
      'Employment',
      // etc...
    ];
    

    and then iterate through it in your template:

    <ul>
        <li 
            *ngFor="let field of fields; let i = index"
            [name]="field"
            [class]="getValidationType(errorArray, field)"
        >
            {{ i + 1 }}
        </li>
    </ul>