[FIXED] How to sort Dynamically generated Form Input Fields in Angular?

Issue

I am using an API and getting and generating my fields according to the response of the API.
When generating the name and email fields are at the end of the form. What I want is to sort this form so that the required fields are shown at the beginning of the form and then the rest of the fields.

    <form (ngSubmit)=" onCreate()" #searchForm="ngForm" style='margin-top: 9rem;' class='form-horizontal'>

    <div class="form-group row">
        <button type="submit" class="btn btn-success px-4 mb-3 ml-4 col-sm-2 mst-2">Create</button>

    </div>
    <div class="form-group row">
        <div class="col-sm-4 mb-2" *ngFor="let prop of classObjresults.attributes ; let i = index">

            <label [for]="prop.name">{{prop.uiText}}</label>

            <input [type]="prop.type | changeInputType" class="form-control" [id]="prop.name"
                [placeholder]="prop.uiText" ngModel [name]="prop.name" required="{{prop.mandatory}}"
                [disabled]="prop.type === 'REFERENCE' || prop.type === 'BOOLEAN' || prop.type === 'ENUM'"
                [ngClass]="{ 'redborder':prop.mandatory}">
        </div>
    </div>

</form>

this is how I generate my form.
and below you can see the output. inputs with red borders are required fields.

This is the output. And I want to bring the red circled input fields in the beginning.

Solution

You can use the orderBy Pipe and supply a function to sort the fields! Please use this working reference example and modify your code!

html

<h1>Order Array Example</h1>

<p *ngFor="let cat of mainCategories | orderBy: sortFn">
  {{ cat.name }} - {{ cat.slug }}
</p>

ts

import { Component, VERSION } from '@angular/core';

export interface Category {
  name: string;
  slug: string;
  description?: string;
  show: boolean;
  mandatory: boolean;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  mainCategories: Category[] = [
    { name: 'Cat3', slug: 'slug3', show: true, mandatory: true },
    { name: 'Cat1', slug: 'slug1', show: true, mandatory: false },
    { name: 'Cat2', slug: 'slug2', show: true, mandatory: true },
  ];

  sortFn = (a: Category, b: Category): number => {
    return a.mandatory === b.mandatory ? 0 : a.mandatory ? -1 : 1;
  };
}

forked stackblitz

Answered By – Naren Murali

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published