Keydown事件不适用于Angular中的选项

时间:2020-07-27 14:20:18

标签: angular angular-forms

我有以下代码,需要在用户按Enter键从选项中进行选择时触发功能。

如果我使用(单击)事件,那么一切都会按预期进行,但是这只会在单击时执行功能,这对UX来说不是很好。

<form (ngSubmit)="onCreatePost(formData.value)" #formData="ngForm" autocomplete="off" class="form">
    <select name="name" ngModel>
        <option value="" disabled selected>Choose language</option>
        <option *ngFor="let language of languageList" (keydown.enter)="getLanguageCode(language.code)">{{ language.name }}</option>                   
    </select>
    <input type="text" name="code" [ngModel]="langCode">
    <button type="submit" class="button-primary" [disabled]="!formData.valid"><i class="fas fa-plus-circle margin"></i>Submit</button>
</form>

3 个答案:

答案 0 :(得分:1)

尝试在(keydown.enter)上使用select而不是每个选项。我在表单上使用它并可以正常工作。

答案 1 :(得分:0)

var app=angular.module("myapp",[]);

app.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
            
             alert("Enter is Pressed");
             event.preventDefault();
            }
        });
    };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myapp">
    <input type="text" my-enter="doSomething()">    
</div>

替代方法是使用标准指令ng-keypress =“ myFunct($ event)”

  $scope.myFunct = function(keyEvent) {
  if (keyEvent.which === 13)
alert('I am an alert');
 }

答案 2 :(得分:0)

尝试在select元素上添加onchange事件侦听器。无论您使用鼠标还是键盘来选择选项,onchange事件都应触发。

相关问题