How to filter an array object in input text - angular I'm trying to make an search bar to filter where the user can search the location/description which I name it "sensor".
roomlistponent.ts
validateForm: FormGroup;
rowData: templogRecord[] = [];
option: any = [];
onLoad() {
this.rowData = record.default.records;
this.option = [];
this.rowData.forEach(room => {
this.option.push({
tooltip: {
formatter: "{a} <br/>{b} : {c}°"
},
toolbox: {
show: true,
feature: {
mark: { show: false },
restore: { show: false },
saveAsImage: { show: false }
}
},
series: [
{
name: room.sensor,
type: 'gauge',
center: ['40%', '70%'],
splitNumber: 10,
radius: '70%',
axisLine: {
lineStyle: {
color: [[0.2, '#48b'], [0.8, '#228b22'], [1, '#ff0000']],
width: 8
}
},
axisTick: {
splitNumber: 10,
length: 12,
lineStyle: {
color: 'auto'
}
},
axisLabel: {
textStyle: {
color: 'auto'
}
},
splitLine: {
show: true,
length: 30,
lineStyle: {
color: 'auto'
}
},
pointer: {
width: 5
},
title: {
show: true,
offsetCenter: [0, '65%'],
textStyle: {
fontWeight: 'bolder'
}
},
detail: {
formatter: '{value}°',
textStyle: {
color: 'auto',
fontWeight: 'bolder'
}
},
data: [{ value: this.tempGenerator(), name: "Temperature" }]
},
{
name: '转速',
type: 'gauge',
center: ['70%', '25%'],
splitNumber: 10,
radius: '40%',
axisLine: {
lineStyle: {
width: 8
}
},
axisTick: {
length: 12,
lineStyle: {
color: 'auto'
}
},
splitLine: {
length: 20,
lineStyle: {
color: 'auto'
}
},
pointer: {
width: 5
},
title: {
show: true,
offsetCenter: [0, '80%'],
textStyle: {
fontWeight: 'bolder',
}
},
detail: {
formatter: '{value}%',
offsetCenter: [0, '55%'],
textStyle: {
color: 'auto',
fontSize: 18,
fontWeight: 'bolder'
}
},
data: [{ value: 1.5, name: "Humidity" }]
}
]
});
});
}
tempGenerator() {
var time = 12;
var num = Math.random() * 100;
var tempBase = Math.round(num);
var fluc = [0, 1, 1, 2, 1, 1, 2.5, 3.5, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
return tempBase * fluc[time];
}
searchData(searchValue: any) {
if (searchValue.length >= 3) {
this.rowData = this.rowData.filter((data: templogRecord) => {
console.log(data['sensor']);
});
} else if (searchValue.length < 1) {
console.log('empty')
}
}
}
roomlist.json
{
"records": [
{
"dateandtime": "2018-06-14 02:24:02",
"sensor": "Nine Seal Area",
"temperature": "25.9",
"humidity": "99.9"
},
{
"dateandtime": "2018-06-14 02:24:02",
"sensor": "Ten Line2",
"temperature": "25.9",
"humidity": "99.9"
},
{
"dateandtime": "2018-06-14 02:22:01",
"sensor": "Eight Line1",
"temperature": "25.9",
"humidity": "99.9"
}
]
}
room-listponent.html
<div class="flex-container">
<div class="date-filter">
<nz-input-group [nzSuffix]="suffixIconSearch">
<input type="text"
nz-input placeholder="Search"
[(ngModel)]="filterSearch"
(ngModelChange)="searchData($event)"
/>
</nz-input-group>
<ng-template #suffixIconSearch>
<i nz-icon nzType="search"></i>
</ng-template>
</div>
<ul class="cards">
<li class="cards__item" *ngFor="let data of option">
<div class="card">
<div echarts [options]="data" [autoResize]="true"></div>
<div class="card__content">
<button class="btn btn--block card__btn">Button</button>
</div>
</div>
</li>
</ul>
</div>
In the searchData
function, I'm trying to make it filtering while typing based in location/description which I named it "sensor".
How to filter an array object in input text - angular I'm trying to make an search bar to filter where the user can search the location/description which I name it "sensor".
roomlist.ponent.ts
validateForm: FormGroup;
rowData: templogRecord[] = [];
option: any = [];
onLoad() {
this.rowData = record.default.records;
this.option = [];
this.rowData.forEach(room => {
this.option.push({
tooltip: {
formatter: "{a} <br/>{b} : {c}°"
},
toolbox: {
show: true,
feature: {
mark: { show: false },
restore: { show: false },
saveAsImage: { show: false }
}
},
series: [
{
name: room.sensor,
type: 'gauge',
center: ['40%', '70%'],
splitNumber: 10,
radius: '70%',
axisLine: {
lineStyle: {
color: [[0.2, '#48b'], [0.8, '#228b22'], [1, '#ff0000']],
width: 8
}
},
axisTick: {
splitNumber: 10,
length: 12,
lineStyle: {
color: 'auto'
}
},
axisLabel: {
textStyle: {
color: 'auto'
}
},
splitLine: {
show: true,
length: 30,
lineStyle: {
color: 'auto'
}
},
pointer: {
width: 5
},
title: {
show: true,
offsetCenter: [0, '65%'],
textStyle: {
fontWeight: 'bolder'
}
},
detail: {
formatter: '{value}°',
textStyle: {
color: 'auto',
fontWeight: 'bolder'
}
},
data: [{ value: this.tempGenerator(), name: "Temperature" }]
},
{
name: '转速',
type: 'gauge',
center: ['70%', '25%'],
splitNumber: 10,
radius: '40%',
axisLine: {
lineStyle: {
width: 8
}
},
axisTick: {
length: 12,
lineStyle: {
color: 'auto'
}
},
splitLine: {
length: 20,
lineStyle: {
color: 'auto'
}
},
pointer: {
width: 5
},
title: {
show: true,
offsetCenter: [0, '80%'],
textStyle: {
fontWeight: 'bolder',
}
},
detail: {
formatter: '{value}%',
offsetCenter: [0, '55%'],
textStyle: {
color: 'auto',
fontSize: 18,
fontWeight: 'bolder'
}
},
data: [{ value: 1.5, name: "Humidity" }]
}
]
});
});
}
tempGenerator() {
var time = 12;
var num = Math.random() * 100;
var tempBase = Math.round(num);
var fluc = [0, 1, 1, 2, 1, 1, 2.5, 3.5, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
return tempBase * fluc[time];
}
searchData(searchValue: any) {
if (searchValue.length >= 3) {
this.rowData = this.rowData.filter((data: templogRecord) => {
console.log(data['sensor']);
});
} else if (searchValue.length < 1) {
console.log('empty')
}
}
}
roomlist.json
{
"records": [
{
"dateandtime": "2018-06-14 02:24:02",
"sensor": "Nine Seal Area",
"temperature": "25.9",
"humidity": "99.9"
},
{
"dateandtime": "2018-06-14 02:24:02",
"sensor": "Ten Line2",
"temperature": "25.9",
"humidity": "99.9"
},
{
"dateandtime": "2018-06-14 02:22:01",
"sensor": "Eight Line1",
"temperature": "25.9",
"humidity": "99.9"
}
]
}
room-list.ponent.html
<div class="flex-container">
<div class="date-filter">
<nz-input-group [nzSuffix]="suffixIconSearch">
<input type="text"
nz-input placeholder="Search"
[(ngModel)]="filterSearch"
(ngModelChange)="searchData($event)"
/>
</nz-input-group>
<ng-template #suffixIconSearch>
<i nz-icon nzType="search"></i>
</ng-template>
</div>
<ul class="cards">
<li class="cards__item" *ngFor="let data of option">
<div class="card">
<div echarts [options]="data" [autoResize]="true"></div>
<div class="card__content">
<button class="btn btn--block card__btn">Button</button>
</div>
</div>
</li>
</ul>
</div>
In the searchData
function, I'm trying to make it filtering while typing based in location/description which I named it "sensor".
- What exactly is your question. How to connect input field with searchData function? – J. S. Commented Sep 2, 2019 at 9:03
- @J.S. search filtering with list items – ABC Commented Sep 2, 2019 at 9:12
- @J.S i updated my code sir – ABC Commented Sep 2, 2019 at 9:13
3 Answers
Reset to default 6Each time you make a search, you're filtering the elements in your array and giving the output to your original array. Consequently, you loose your data. Why don't you create 2 variables:
- The original array which doesn't change ( containing your data ) which should be in a provider but in our example we'll declare it in your ponent.
- The filtered array which you're going to display
searchData(searchValue: any) {
this.filteredData = this.rowData.filter((item: templogRecord) => {
return item.sensor.toLowerCase().includes(searchValue.toLowerCase());
});
}
I would remend this solution (Based on materials autoplete: https://stackblitz./angular/lndebkoyare?file=app%2Fautoplete-filter-example.ts)
In your ponent:
import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
/**
* @title Filter autoplete
*/
@Component({
selector: 'autoplete-filter-example',
templateUrl: 'autoplete-filter-example.html',
styleUrls: ['autoplete-filter-example.css'],
})
export class FilterExample implements OnInit {
// your control for input
searchControl = new FormControl();
// your whole set of options
options: string[] = ['One', 'Two', 'Three'];
// your current result based on filters input
filteredOptions: Observable<string[]>;
ngOnInit() {
this.filteredOptions = this.searchControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
}
}
Your template would look like this:
<div class="flex-container">
<div class="date-filter">
<nz-input-group [nzSuffix]="suffixIconSearch">
<input type="text"
nz-input placeholder="Search"
[formControl]="searchControl"
/>
</nz-input-group>
<ng-template #suffixIconSearch>
<i nz-icon nzType="search"></i>
</ng-template>
</div>
<ul class="cards">
<li class="cards__item" *ngFor="let data of filteredOptions | async">
<div class="card">
<div echarts [options]="data" [autoResize]="true"></div>
<div class="card__content">
<button class="btn btn--block card__btn">Button</button>
</div>
</div>
</li>
</ul>
Every time value on input changes the observable valueChanges
on searchControl
emits the current value of this input field. This part map(value => this._filter(value))
returns a filtered subset of your options array. Which can be displayd using the async pipe: <li class="cards__item" *ngFor="let data of filteredOptions | async">...</li>
DO NOT USE find
or includes
, because these are not supported by the Internet Explorer.
How about using javascript's filter
function? See an example below.
The following example assumes that you are targeting the sensor
element in the object.
Click here for a DEMO
const test = {
"records": [
{
"dateandtime": "2018-06-14 02:24:02",
"sensor": "Nine Seal Area",
"temperature": "25.9",
"humidity": "99.9"
},
{
"dateandtime": "2018-06-14 02:24:02",
"sensor": "Ten Line2",
"temperature": "25.9",
"humidity": "99.9"
},
{
"dateandtime": "2018-06-14 02:22:01",
"sensor": "Eight Line1",
"temperature": "25.9",
"humidity": "99.9"
}
]
};
let found = [];
const searchTerm = 'Eight Line1';
found = test.records.filter(function(element) {
return element.sensor.toLowerCase() == searchTerm.toLowerCase();
});
console.log('found ' , found[0]);
Update
To perform a partial search (searching for a part of the string), you can safely use indexOf
. See an example below,
console.log("Eight Line1".indexOf("Ei") !== -1);
Hope this helps,
Thanks.