how to search in signal list in angular

I have a list of signal type.
searchModelDriver: string = '';
driverList = signal<any[]>([
{ fullName: 'test1' },
{ fullName: 'test2' },
{ fullName: 'test3' },
])
I also have a simple input in the html that I want to search in.
<div>
<input type="text" pInputText placeholder="Search Driver ..." [(ngModel)]="searchModelDriver" />
</div>
<div *ngFor="let item of driverList(); let i = index;">
{{item.fullName}}
</div>
Now my problem is that no matter what I do, I can't get into this signal and perform the search operation
Please help me
Answer
We can convert the property used for ngModel
to a signal, so that when this value changes we use a computed
to perform the search.
The computed, will have two signals inside it, one the list and the other the search keyword. We use filter
array operation to filter the list.
We are using computed
which is a non writable signal, which is great for creating readonly derived state from the source signals inside the callback.
If you want a writable derived state, then you can use linkedSignal
which does the same thing as computed, but is writable also.
export class App {
searchModelDriver = signal('');
driverList = signal<any[]>([
{ fullName: 'test1' },
{ fullName: 'test2' },
{ fullName: 'test3' },
]);
driverListSearch = computed(() => {
return this.driverList().filter((item: any) =>
item.fullName.includes(this.searchModelDriver())
);
});
}
Full Code:
import { Component, signal, computed } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [FormsModule],
template: `
<div>
<input type="text" pInputText placeholder="Search Driver ..." [(ngModel)]="searchModelDriver" />
</div>
@for(item of driverListSearch(); let i = $index; track i) {
<div> {{item.fullName}} </div>
}
`,
})
export class App {
searchModelDriver = signal('');
driverList = signal<any[]>([
{ fullName: 'test1' },
{ fullName: 'test2' },
{ fullName: 'test3' },
]);
driverListSearch = computed(() => {
return this.driverList().filter((item: any) =>
item.fullName.includes(this.searchModelDriver())
);
});
}
bootstrapApplication(App);
Read more
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles