Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 614
yoursweater Avatar asked Jun 11 '18 21:06

yoursweater


2 Answers

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)">
like image 184
Forrest Avatar answered Oct 16 '22 10:10

Forrest


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)'
like image 20
Akshay Rana Avatar answered Oct 16 '22 11:10

Akshay Rana