Uak
Uak

Reputation: 86

Angular 2 - [attr.selected] works but select nothing

I have a simple problem but i don't find a solution

I have this select:

<select name="projectObjectUpdate" [ngFormControl]="_projectAmountForm.controls['projectObject']"
                                            class="form-control form-control-select2-field">
                                        <option *ngFor="let object of _projectObjectList" [ngValue]="object" [attr.selected]="object.id === _projectAmountForm.controls['projectObject'].value.id ? true : null">
                                            {{object.descriptions[_user.language]}}
                                        </option>
                                    </select>

In the HTML code, good option is selected

but nothing is selected on screen

anyone knows the problem ?

Upvotes: 1

Views: 5971

Answers (2)

Herr Derb
Herr Derb

Reputation: 5387

You also could just bind ngModel on your select element.

<select name="projectObjectUpdate" [ngModel]="_projectAmountForm.controls['projectObject'].value.id" [ngFormControl]="_projectAmountForm.controls['projectObject']"
        class="form-control form-control-select2-field" >
    <option *ngFor="let object of _projectObjectList" [ngValue]="object" >
        {{object.descriptions[_user.language]}}
    </option>
</select>

This will always select the option element with the same value as _projectAmountForm.controls['projectObject'].value.id

EDIT:

Sorry, yes ngValue was wrong! I meant ngModel. Corrected.

Upvotes: 3

Bnayal
Bnayal

Reputation: 19

Try binding to the [selected] attribute, like that:

<option *ngFor="let object of _projectObjectList" [ngValue]="object" [selected]="object.id === _projectAmountForm.controls['projectObject'].value.id">

Upvotes: -1

Related Questions