1

I was having problem when trying to sort the dropdown values in Angular Typescript. I am trying to sort by staffName:

<div class="row">
            <div class="form-group col-md-2">
                <strong><label class="form-control-label" jhiTranslate="staff.staffReportingOfficer" for="field_staffReportingOfficer">Staff Reporting Officer</label></strong>
            </div>
            <div class="form-group col-md-4">
                <select class="form-control" id="field_staffReportingOfficer" name="staffReportingOfficer" [(ngModel)]="staff.staffReportingOfficer" (change)="roDropdownOnChange()">
                    <option [ngValue]='' disabled>Please select an Option</option>
                    <option [ngValue]="reportingOfficerOption.id === staff.reportingOfficer?.id ? staff.reportingOfficer.staffName : reportingOfficerOption.staffName" *ngFor="let reportingOfficerOption of reportingOfficers | orderBy: 'staffName'">{{reportingOfficerOption.staffName}}</option>
                </select>
            </div>
        </div>

My staffs array contains data like A, B, C, D, E, aaaa. Then it is showing the exact same sequence as above.

My desired output will be like A, aaaa, B, C, D, E. Any ideas?

2
  • I don't think Angular has an OrderBy pipe anymore. You will need to manually sort your array Commented Mar 28, 2019 at 6:17
  • Check this example, I think this is what you are looking for: stackblitz.com/edit/angular-yfw5ia?file=app/… Commented Mar 28, 2019 at 6:20

2 Answers 2

1

Angular no longer has the OrderBy pipe. You may refer to this for more details.

You will need to manually sort your reportingOfficers array. It seems it is an array of objects?

To perform a case insensitve sort, we will need to supply a custom sorting function by converting staffName values to lower case.

reportingOfficers.sort((a, b) => a['staffName'].toLowerCase().localeCompare(b['staffName'].toLowerCase()));
console.log(reportingOfficers);

This is how it is done with vanilla JavaScript/TypeScript (without relying on additional libraries such as Lodash).

Sign up to request clarification or add additional context in comments.

Comments

1

You can use lodash for this

var arr = ['A', 'B', 'C', 'a', 'b']

console.log(_.sortBy(arr, function (val) {
	return val.toLowerCase();
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.