因此,当我按下Enter键(它成功运行performSearch函数)时,我的代码起作用了,但是当我尝试通过单击“提交”按钮来运行该函数时,出现了错误:



这是我的代码:

<mat-form-field (ngSubmit)='performSearch($event)' color='primary' id='search-input' class='full-width' appearance='outline'>
    <mat-label color='red'>Search</mat-label>
    <input #searchBar matInput  [(ngModel)]='searchValue' name='searchBar' [value]='searchValue' (keyup.enter)='performSearch($event)'>
 </mat-form-field>

 <button mat-raised-button color="primary" (click)='performSearch(searchBar.value)' id='submit-search' type='submit' for='searchBar'>Submit</button>

我想要的是一种获取#searchBar'值并将其传递到单击按钮时触发的performSearch()函数的方法。我怎么做?

最佳答案

您正在使用var searchValue在搜索栏中进行两种方式的绑定(bind),因此您只需要单击“提交”就只需更改此变量即可。
只需替换您的点击事件

(click)='performSearch(searchBar.value)' to
(click)='performSearch(searchValue)'

关于javascript - 如何在Angular 6中将输入值传递到表单提交的函数中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50806610/

10-11 06:13