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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50806610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:41:08  来源:igfitidea点击:

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

javascriptangular

提问by yoursweater

So my code works when I hit enter (it runs the performSearchfunction successfully), but when I try to run the function by hitting my submit button I get the error:

所以我的代码在我按下回车键时工作(它performSearch成功运行了该函数),但是当我尝试通过点击提交按钮运行该函数时,我收到错误消息:

cannot read property error of undefined

无法读取未定义的属性错误

Here's my code:

这是我的代码:

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

All I want is a way to grab the #searchBar' value and pass it into the performSearch()function that fires when I click the button. How do I do that?

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

回答by Robin gupta

You are doing two way binding in the search bar with var searchValueso you need to change only pass this var on click of submit. Just replace your click event

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

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

回答by Akshay Rana

This is because you are sending the event object on form submit, so you'll get the complete Event object.

这是因为您在表单提交时发送事件对象,因此您将获得完整的 Event 对象。

(ngSubmit)='performSearch($event)'

If you just want one value, use your template reference variable of input as you are using in click event,

如果您只想要一个值,请使用您在单击事件中使用的输入模板引用变量,

(ngSubmit)='performSearch(searchBar.value)'

回答by Sidhanshu_

 (click)="performSearch(searchValue)"

It will work, because you've model in searchbar input, it will send that value through click function!

它会起作用,因为您在搜索栏输入中建立了模型,它将通过单击功能发送该值!

回答by Forrest

If you are working with a piece that needs to pass it's own value into a method, this will do the trick:

如果您正在处理需要将其自身的值传递给方法的部分,则可以这样做:

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