Sunstrike527
Sunstrike527

Reputation: 607

How to add custom input option to select?

I'm working with <mat-select> and I need list of options where the last option would be a text input with placeholder Add your custom option. User can select one of the options or click the last option (which is input) and text own option , once he texted he clicked outside of select and value has been set what User has texted.

the problem is when the user add push space to add whitespace, dropdown closes.

<select>
  <option value="option 1"> option 1 </option>
  <option value="option 2"> option 2 </option>
  <option> <input type="text" placeholder="own option" /></option>
</select>

Upvotes: 0

Views: 452

Answers (1)

JayNews
JayNews

Reputation: 61

Adding an $event.stopPropagation should be adequate. In the code block below I used it twice:

  1. on the (click) event, so when the user clicks on the text input area, the select menu does not close
  2. on the (keydown) event as the mat-select directive listens for the space key and closes the menu if it receives it.

<mat-select>
  <mat-option *ngFor="let food of foods" [value]="food.value">
    {{ food.viewValue }}
  </mat-option>
  <mat-option>
    <input
      type="text"
      placeholder="Add your custom option"
      (click)="$event.stopPropagation()"
      (keydown)="$event.stopPropagation()"
    />
  </mat-option>
</mat-select>

Upvotes: 1

Related Questions