1

I want to select in <select> an option which I defined in component. But when I want to print this in console I get undefined. My code:

component.html:

<div class="row">
    <div class="form-group col-md-6">
        <label>Select option:</label>
        <select class="form-control" [(ngModel)]="selectedOption">
            <option *ngFor="let item of options" [value]="item">{{ item.display }}</option>
        </select>
    </div>
</div>

<button type="button" (click)="showOption()">Show selected option</button>

component.ts:

selectedOption: any;

sortOptions = [
    {
        value: 'option1',
        display: 'First option'
    },
    {
        value: 'option2',
        display: 'Second option'
    }
];

showOption(): void {
    console.log(this.selectedOption.value);
}

When I try print console.log(this.selectedOption.value); I get "undefined" and when I try to print console.log(this.selectedOption) I get "[option Option]"

I don't know how to resole it.

2 Answers 2

1

Try with [ngValue] instead [value]:

<select [(ngModel)]="selectedOption">
   <option value=""></option>
   <option *ngFor="let item of options" [ngValue]="item">
     {{item.display}}
   </option>
</select>
Sign up to request clarification or add additional context in comments.

4 Comments

It works, thanks. What is a different between value and ngValue?
There's no documentation which explain in details ngValue, but if you want to use objects in option you have to do it via [ngValue] for the rest cases you can use [value]
And what if I use ReactiveFormsModule instead of FormsModule — so I have formControlName instead of the ngModel — what should I do to make Angular to select selectedOption? Now I have options array and selectedOption is one of this array items... but Angular is not making this option as selected :(
It stays the same just replace [(ngModel)] with formControlName and it should works.
0

You can also use this :

 <select [(ngModel)]="selectedOption">
   <option value=""></option>
   <option *ngFor="let item of sortOptions" [value]="item.id">
     {{item.display}}
   </option>
</select>

[value] for string values and [ngValue] for all types

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.