繁体   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