简体   繁体   中英

Angular 2 how can i add click event inside option?

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;
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM