简体   繁体   中英

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

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

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?

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

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

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

(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)'
 (click)="performSearch(searchValue)"

它将起作用,因为您已经在搜索栏中输入了模型,它将通过click函数发送该值!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM