Uak Uak - 2 months ago 20
HTML Question

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 ?

Answer

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.

Comments