在Angular 2中,如何在按Enter键时提交输入类型="文本"值?

Koe*_*uck 34 angular

我正在我的Angular 2应用程序中构建一个搜索框,尝试在点击"Enter"时提交值(表单不包含按钮).

模板

<input type="text" id="search" class="form-control search-input" name="search" placeholder="Search..." [(ngModel)]="query" (ngSubmit)="this.onSubmit(query)">
Run Code Online (Sandbox Code Playgroud)

使用简单的onSubmit函数进行测试......

export class HeaderComponent implements OnInit {
  constructor() {}

  onSubmit(value: string): void {
    alert('Submitted value: ' + value);
  }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,ngSubmit似乎不起作用.那么解决这个问题的'Angular 2方式'是什么?(最好没有像隐藏按钮这样的黑客)

God*_*her 100

(keyup.enter)="methodInsideYourComponent()" 在输入标记内添加此内容

  • [Angular Docs](https://angular.io/docs/ts/latest/guide/user-input.html#!#key-event-filtering-with-key-enter-)中也提到了这一点. (4认同)
  • 另外,您可以通过`methodInsideYourComponent($ event)`发送输入信息,并在方法`evt.target.value上访问它. (2认同)