1. Create an Angular Component
ng generate component search
2. App Component (app.component.ts)
Define the data and the search term, and filter the data based on the search term:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
searchTerm: string = ''; // Holds the search term
data: string[] = [
'Angular Tutorial', 'React Tutorial', 'Vue Tutorial',
'Svelte Tutorial', 'JavaScript Basics', 'TypeScript Basics'
];
// Filter the data based on the search term
get filteredData() {
return this.data.filter(item => item.toLowerCase().includes(this.searchTerm.toLowerCase()));
}
}
3. App Component Template (app.component.html)
Create an input field for the search and display filtered results:
<div>
<input type="text" [(ngModel)]="searchTerm" placeholder="Search..." />
<ul>
<li *ngFor="let item of filteredData">{{ item }}</li>
</ul>
</div>
4. App Module (app.module.ts)
Import FormsModule to enable two-way data binding with ngModel:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Import FormsModule
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule], // Include FormsModule
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
5. Run the Application
ng serve