1

I am implementing search functionality in Angular. I am displaying details from an array into a div. What I want is to display only those details whose name I type in searchbox. I am trying filter method on array and this is what I have tried:

Component.ts:

import { Component, OnInit } from '@angular/core';
import { Employee } from '../Employee';
import {NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';


@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
  
  constructor() { }
  

  ngOnInit(): void {
  }

  filteredEmployees:Employee[]=[]

  searchText=""

  employeeList:Employee[]=
  [
    {
    id:1,
    name:"abc def",
    salary:20000,
    permanent:true,
    department:{id:1, name:"Payroll"},
    skill:[{id:1 , value:"HTML"},{id:2 , value:"CSS"},{id:1 , value:"JS"}],
    dateOfBirth:new Date('01/03/2002')
    },
    {
    id:1,
    name:"ssss gggg",
    salary:40000,
    permanent:false,
    department:{id:2, name:"Internal"},
    skill:[{id:1 , value:"HTML"},{id:2 , value:"CSS"},{id:1 , value:"JS"}],
    dateOfBirth:new Date('21/03/2006')
    },
    {
    id:1,
    name:"asdf zxcv",
    salary:60000,
    permanent:true,
    department:{id:3, name:"HR"},
    skill:[{id:1 , value:"HTML"},{id:2 , value:"CSS"},{id:1 , value:"JS"}],
    dateOfBirth:new Date('16/05/2010')
    }
  ];

  searchKey(data:string)
  {
    this.searchText=data;
  }

  search()
  {
    this.filteredEmployees = this.employeeList.filter((element)=>{
      return element.name.toLowerCase()==this.searchText.toLowerCase();
    });
  }

}

This is my html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <b>Employees List</b>
    <br>
    <br>

            <div class="form-group">
                <label for="search">Search</label>
                <input type="text" (keyup)="search()" id="search" [(ngModel)]="searchKey(searchText)"  placeholder="Find by name" ngModel>
            </div>

    <div class="row" *ngFor="let e of employeeList">
        <div class="block" style="width:300px;height:100px;border:1px solid #000;">
            <h4>{{e.name}}</h4>
            <h6>₹ {{e.salary}}</h6>
            <app-employee-info></app-employee-info>
        </div>
        <br>
        <br>
    </div>
    
</body>
</html>

I am trying to two way bind searchKey with search text box and its keyup event should call the search function. search then filters based on the input. But I get this error : Unexpected token '=' at column 22 in [searchKey(searchText)=$event]

Also one more thing ::How do I connect my display div to my search box so that it only displays based on the filtered results??

4
  • In your input [(ngModel)]="searchText" or [ngModel]="searchText" (ngModelChange)="searchKey($event)"? Commented Apr 29, 2021 at 10:16
  • @Kitsune66 got it, thanks a lot Commented Apr 29, 2021 at 10:23
  • good. Also, if you use ngModelChange you can remove (keyUp) and in the searchKey method just call search after updating current search value. ` searchKey(data: string) { this.searchText = data; this.search(); }` Commented Apr 29, 2021 at 10:29
  • <div class="row" *ngFor="let e of filteredEmployees"> to show filtered employees. And update search method to return all employees if search is empty. Commented Apr 29, 2021 at 10:41

2 Answers 2

2

You should create a very simple procedure for this. on your Search() clone the employee to other array.

ngOnInit() {
    this.cEmployee = this.employeeList;
  }

  search() {
    var x = [];

    if (this.searchText == '') {
      this.employeeList = this.cEmployees;
    } else {
      this.filteredEmployees = this.employeeList.filter((element) => {
        element.name.toLowerCase() == this.searchText.toLowerCase();
      });

      this.employeeList = this.filteredEmployees;
    }
  }
Sign up to request clarification or add additional context in comments.

6 Comments

unused variable 'x' :)
@saper should use filteredEmployees in the template. No need to "clone" employeeList.
what does x store?
it's a typo, ignore it
Hey @sapter. cloning is the best way to do it. cause it wont change the original array and if user clears the search text the div will display all elements.
|
1

full solution from comments.

Update input and *ngFor

  <input type="text" id="search" [ngModel]="searchText" (ngModelChange)="searchKey($event)" placeholder="Find by name"
    ngModel>

........

<div class="row" *ngFor="let e of filteredEmployees">

Update ts file

  ngOnInit(): void {
    this.search();
  }


  searchKey(data: string) {
    this.searchText = data;
    this.search();
  }

  search() {
    this.filteredEmployees = this.searchText === ""? this.employeeList : this.employeeList.filter((element) => {
      return element.name.toLowerCase() == this.searchText.toLowerCase();
    });
  }

4 Comments

Man, this works perfectly. Just one tiny issue though.The div is empty unless u search something or type in textbox.Then it displays everything. Why is that??
Btw , thanks for the help.Really appreciate it.
sorry for delay @sapter. You need to populate filteredEmployees when component loads. just run the search() method on component init. ngOnInit(): void { this.search(); }. Updated my answer.
np , I figured it out. Appreciate the reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.