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 >
<button type="submit" >Create</button>
</div>
<div >
<div *ngFor="let prop of classObjresults.attributes ; let i = index">
<label [for]="prop.name">{{prop.uiText}}</label>
<input [type]="prop.type | changeInputType" [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.
CodePudding user response:
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;
};
}