Angular 2如何在选项中添加click事件? [英] Angular 2 how can i add click event inside option?

查看:96
本文介绍了Angular 2如何在选项中添加click事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的HTML,当我点击选项new-item时,它会打开输入类型框,然后我输入值想要添加到选择选项

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>

我的类型脚本是

addSelect() {
        this.edited = true;
}
constructor() {
    this.edited = false;
}


推荐答案

你不能添加这样的一个事件到<选项>

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

您可以看到事件不会在所有浏览器中触发(它使用的唯一浏览器是< ie11和Firefox):

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>

标记不会向下传播任何点击事件。因此,您尝试在选项中分配的任何点击事件都不起作用。最好的办法是查看 onChange()回调中收到的值,然后打开另一个允许用户输入数据的组件。您甚至可以使用 window.prompt()来获取此类数据。

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.

您可以这样做:

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

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

有关实施此方法的更多信息,请参阅:如何在选择中获得新选择?在Angular 2?

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

这篇关于Angular 2如何在选项中添加click事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆