1
votes

Goal

I want to pre-select an option of a select with [ngValue] and [(ngModel)] with the values being an object TypeConge:

{ "id": 2, "libelle": "Holidays" }

First Try

            <div class="form-group col-12">
                <label class="font-weight-bold" for="typeConge"> Type congé </label>
                <select class="form-control" id="typeConge" name="typeConge"  [(ngModel)]="conge.typeConge" >
                    <option [ngValue]="null"></option>
                    <option [ngValue]="typeCongeOption" *ngFor="let typeCongeOption of typeConges; trackBy: trackTypeCongeById">{{typeCongeOption.libelle}}</option>
                </select>
            </div>
            {{conge.typeConge| json}}

Problem: The select option is not preselected.

Second Try

            <div class="form-group col-12">
                <label class="font-weight-bold" for="typeConge"> Type congé </label>
                <select class="form-control" id="typeConge" name="typeConge" [compareWith] = 'customCompareTypeConge' [(ngModel)]="conge.typeConge" >
                    <option [ngValue]="null"></option>
                    <option [ngValue]="typeCongeOption" *ngFor="let typeCongeOption of typeConges; trackBy: trackTypeCongeById">{{typeCongeOption.libelle}}</option>
                </select>
            </div>
            {{conge.typeConge| json}}

...

customCompareTypeConge(tc1: TypeConge, tc2: TypeConge){
        return tc1.id == tc2.id;
    }

Problem: In the console I find: Cannot read property 'id' of null

EDIT

Link to stackblitz.

EDIT 2

A full explanation of this issue can be found at this adress.

Could you help me please?

Thanks!

1
Have you tried [(ngModel)]="conge.typeConge.id" [ngValue]="typeCongeOption.id"? - Marshal
I just tried. It's not working. In any case, I would prefer to directly get the object through the select. - Manuela CodingPadawan
Can you please create a stackblitz of the problem statement? - Pankaj Parkar
Do you set the initial value like this: this.conge.typeConge = this.typeConges[0]? Or this.conge.typeConge = null if you want to select the first option. - ConnorsFan
@ConnorsFan No. The initial value come from a request to a server. So the this.conge.typeConge contain the object typeConge { "id": 2, "libelle": "Holidays" } for example. - Manuela CodingPadawan

1 Answers

2
votes

I think you are confused on how the relationship between ngModel and ngValue work to default the select. It has to be a 1:1 explicit comparison between the ngModel value and the ngValue.

You appear to be using typeConges to define your options in your loop with typeCongeOption as the option value which is a complete index item, and then using conge.typeConge to define your ngModel... there has to be a 1 === 1 comparison between these two, you cannot compare complete index items to a value and expect a match.

Please review this stackblitz example.

https://stackblitz.com/edit/angular-13wnyq?embed=1&file=app/select-overview-example.ts