如何将输入值传递给 Angular 6 中表单提交的函数?

you*_*ter 8 javascript angular

所以我的代码在我按下回车键时工作(它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>
Run Code Online (Sandbox Code Playgroud)

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

小智 8

您正在搜索栏中进行两种方式的绑定,var searchValue因此您只需在单击提交时更改传递此变量。只需替换您的点击事件

(click)='performSearch(searchBar.value)' to
(click)='performSearch(searchValue)'
Run Code Online (Sandbox Code Playgroud)