Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 554
niranchan Avatar asked Feb 15 '17 05:02

niranchan


People also ask

How does Angular handle click event?

Events are handled in Angular using the following special syntax. Bind the target event name within parentheses on the left of an equal sign, and event handler method or statement on the right. Above, (click) binds the button click event and onShow() statement calls the onShow() method of a component.

What is $event in Angular?

The $event object often contains information the method needs, such as a user's name or an image URL. The target event determines the shape of the $event object. If the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target.

Can we use two events together in Angular?

Turns out, you totally can. Run this demo in my JavaScript Demos project on GitHub. In Angular 1.


1 Answers

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?

like image 152
Zze Avatar answered Sep 21 '22 09:09

Zze