Jur
Jur

Reputation: 185

Input value not changing in Angular

I have a custom component where the user can search for values with a dropdown/input combination and click the result or scroll and search in the dropdown and click the value, this will set the input value to the clicked dropdown value.

Assume the values are: ['foo', 'bar', 'fee']

If I click 'foo' in the dropdown, the input value will as expected change to 'foo'. However, if then I backspace a bit to 'f' and then click 'foo' again, it will set the variable to 'foo', but it won't update the dropdown value.

If my value was 'foo', I backspaced and I clicked 'fee', it does update like it should.

What is the problem of my value not updating in the input?

search-select.html:

<div>
    <input type="text"
        (input)="filterDropdown()"
        [(ngModel)]="filterValue" [value]="selectedItemName"/> <-- no change here
        {{selectedItemName}} <-- does change here (but I don't want it here)
    <div>
        <div *ngFor="let item of filteredItems" (click)="setItem(item)">
            {{item.name}}
        </div>
</div>

search-select.ts:

public setItem(item): void {
        this.selectedItemName = item[this.itemName];
}

Upvotes: 6

Views: 12806

Answers (3)

Sami Haroon
Sami Haroon

Reputation: 909

Try this this works on native html select tag. HTML:

Use (change)="selectValue($event)" on <select> 
Use directive [(ngModel)]="selectedValue" on <select> 

TS:

selectedValue: any;
selectValue(ev){
   this.selectedValue = ev.target.value;
}

Upvotes: 5

Jur
Jur

Reputation: 185

Found the solution

(input)="filterDropdown($event.target.value)"

and in the ts file:

this.selectedItemName = value;

Upvotes: 2

ussefshahid
ussefshahid

Reputation: 158

Try to use (change)=.. instead of (input)=..

Upvotes: 0

Related Questions