簡體   English   中英

如何在Angular 6中將輸入值傳遞到表單提交的函數中?

[英]How do you pass input value into a function on form submit in Angular 6?

因此,當我按下Enter鍵(它成功運行了performSearch函數)時,我的代碼起作用了,但是當我嘗試通過點擊我的Submit按鈕來運行該函數時,我得到了錯誤:

無法讀取未定義的屬性錯誤

這是我的代碼:

<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在搜索欄中進行兩種方式的綁定,因此您只需要更改一次單擊提交即可通過此var。 只需替換您的點擊事件

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

這是因為您要在表單提交中發送事件對象,所以您將獲得完整的事件對象。

(ngSubmit)='performSearch($event)'

如果您只想要一個值,請像在click事件中一樣使用輸入的模板引用變量,

(ngSubmit)='performSearch(searchBar.value)'
 (click)="performSearch(searchValue)"

它將起作用,因為您已經在搜索欄中輸入了模型,它將通過click函數發送該值!

如果您正在處理需要將其自身的值傳遞給方法的部分,則可以做到這一點:

<input type="number" value="{{myValue}}" (change)="updateMyValue($event.target.value)">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM