Reputation: 77
I'm trying to search the product based on the string passed by the user
getItems(): void {
let search = event.target.value;
if (search && search.trim() != '') {
this.productService.getProducts(search).subscribe((products) => {
console.dir(products);
}, (err) => {
console.log(err);
});
}
When I try to search by passing query it is showing below error
ERROR TypeError: Cannot read property 'target' of undefined
I'm not able to figure out where I went to wrong . Could any one please help me
Upvotes: 0
Views: 713
Reputation: 1863
Here is the possible way to do this the most people using two way data binding only.It is used to get data and bind data.
First way:-
Html File,
<input [(ngModel)]="searchTxt" name="searchTxt" (keyup)="getItems()" />
Typescript file,
public searchTxt:any;
constructor(){
//this.searchTxt="some value"; //here you can assign value to search box
}
getItems(): void {
let search = this.searchTxt; // here iam accessing value from textbox.
if (search && search.trim() != '') {
this.productService.getProducts(search).subscribe((products) => {
console.dir(products);
}, (err) => {
console.log(err);
});
}
Second way:- From your code you missed some minor part, here you will see.
Html File,
<input (keyup)="getItems($event)" />
Typescript file,
getItems(): void { //here you misssed to recieve an argument to a function calling statement
so change like this
getItems(event): void { //here iam recieving argument used some variable name
let search = event.target.value;
if (search && search.trim() != '') {
this.productService.getProducts(search).subscribe((products) => {
console.dir(products);
}, (err) => {
console.log(err);
});
}
I hope you understand what you missed some line your code and also how to use two way data binding.
While using two way binding [(ngModel)]
you have to include FormsModule
in app.module.ts
file,
Upvotes: 1
Reputation: 3593
Assuming there is an event... It shall be passed into the function
getItems(event)
Furthermore. Its a good practise to check the property before using it. I mean target property of event object
Event binding might be assign differently. But in your case - it might be KeyUp of the input field or Click events on the button (but then you need to refer to the field)
<input (keyup)="getItems($event)" />
or
<input #my-input />
<button (click)="getItems($event)" />
in the second example you don't need $event - because it will not refer to the value. Yet you need to use ViewChild decorator function to get the value from the input
Upvotes: 1