7

This is my html,When i click option "new-item" it will open input type box , and then i enter value it want to add to select option

<form (submit)="addItem()">
    <input type="text" [(ngModel)]="add.name" name="name">
    <input type="text" [(ngModel)]="add.price" name="price">
    <input type="text" [(ngModel)]="add.description" name="description">
    <select [(ngModel)]="add.type" name="room-type">
        <option [value]="c">Select</option>
        <option>BreakFast</option>
        <option>Lunch</option>
        <option>Dinner</option>
        <option><button (click)="addSelect()">Add-item</button></option>
        <input *ngIf='edited' type="text" >
   </select>

and my type script is,

addSelect() {
        this.edited = true;
}
constructor() {
    this.edited = false;
}
M Hamza Javed
  • 1,269
  • 4
  • 17
  • 31
niranchan
  • 296
  • 1
  • 2
  • 16
  • 1
    Why do you need such event ? click will anyway make it selected why not use ng-change then. – Vinod Louis Feb 15 '17 at 05:52
  • I want to add select option manually from output. how can i get details – niranchan Feb 15 '17 at 05:56
  • But i can't need this one. I need while i click add-item option new input box want to open. In this input box i enter value, this value can be stored to select option – niranchan Feb 15 '17 at 06:13

1 Answers1

9

You can't add such an event to an <option>.

You can see that the event doesn't fire in all browsers (the only browsers it works in is < ie11 and Firefox):

$("#trig").click((event) => console.log(event));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option>default</option>
  <option id="trig">trigger</option>
</select>

The tag does not propagate down any click events. So any click events you try and allocate inside an option will not work. Your best bet is to look at the value you receive in the onChange() callback and then turn on another component which allows the user to enter data. You could even use a window.prompt() to get such data.

You can instead do this:

<select (change)="onChange($event.target.value)">

onChange(val) {
    console.log(val);
    this.edited = false;
}

For further information on implementing this approach, see: How can I get new selection in "select" in Angular 2?

Community
  • 1
  • 1
Zze
  • 18,229
  • 13
  • 85
  • 118
  • But i can't need this one. I need while i click add-item option new input box want to open. In this input box i enter value, this value can be stored to select option – niranchan Feb 15 '17 at 06:11
  • 1
    The ` – Zze Feb 15 '17 at 06:17
  • @chan I know this is a disappointing conclusion, however at the end of last year I spent a week at work trying to get the exact same functionality in a project. I ended up using the above method. Glad it solved your issue. – Zze Feb 15 '17 at 06:25