简体   繁体   中英

Sorting a drop down list

I'm having trouble sorting the drop down list when the user select the type of sorting that he want with the radio button. If he select Ascendant then the list will be sorted from the lowest number to the highest. If he select Descendant then It will be the highest number to the lowest.

在此处输入图像描述

在此处输入图像描述

this is my code

<div *ngIf="!estNom" id="choix" class="row">

    <h1 class="col-12"> Les Citoyens </h1>

    <section class="col-12">

        <h2>Sélection Par NAS:</h2>

       
        <select (change)="surSelection($event.target.value)">

            <option selected disabled hidden>Choisissez:</option>
            <option *ngFor="let cito of citoyens" [value]="cito.id">{{cito.id}} : {{cito.nom}}</option>

        </select>

        <button (click)="activerSelectionNom()"> Trier Par Nom </button>

        <section >

            <input type="radio" id="Ascendant" name="radio1" value="Ascen">
            <label for="Ascen">Ascendant</label><br>
            <input type="radio" id="Descendant" name="radio2" value="Descen">
            <label for="Descen">Descendant</label>

        </section>
       
    
    </section>

   
</div>

Call this function in the callback function of radio value changed event.

function sortCitoyens(citoyens, isAsc) {
    if(isAsc){
        citoyens.sort((a,b)=>a.id-b.id)
    }else{
        citoyens.sort((a,b)=>b.id-a.id)
    }
}

some one posted the answer and then deleted it but I got the time to do it and it works so thank you all for the help:)

 <section class="col-12">

        <h2>Sélection Par Nom:</h2>

            <select (change)="surSelection($event.target.value)">

                <option value="" selected disabled hidden>Choisissez:</option>
                <option *ngFor="let cito of citoyens.sort()" [value]="cito.id">{{cito.nom}} : {{cito.id}}</option>
    
            </select>

            <button (click)="activerSelectionNAS()"> Trier Par NAS </button>
    
            <section>
    
               
                <input type="radio" id="asc" name="sort" (click)="sort('asc')"> &nbsp;
                <label for="asc">Ascendant</label><br>

                <input type="radio" id="desc" name="sort" (click)="sort('desc')" > &nbsp;
                <label for="desc">Descendant</label>
                

            </section>
           

    </section>

sort(type: string) {
  const sortList = (a: any, b: any) => a.nom.toLowerCase().localeCompare(b.nom.toLowerCase());

  this.citoyens = type === "asc"
    ? this.citoyens.sort((a: any, b: any) => sortList(a, b))
    : this.citoyens.sort((a: any, b: any) => sortList(b, a));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM