te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Angular How to filter array data by searching in input - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular How to filter array data by searching in input - Stack Overflow

programmeradmin3浏览0评论

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".

Share Improve this question edited Dec 25, 2022 at 2:02 Melchia 24.3k23 gold badges108 silver badges129 bronze badges asked Sep 2, 2019 at 7:55 ABCABC 8326 gold badges20 silver badges45 bronze badges 3
  • 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
Add a ment  | 

3 Answers 3

Reset to default 6

Each 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:

  1. 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.
  2. 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.

发布评论

评论列表(0)

  1. 暂无评论