2

Доброго времени суток! Делаю поиск на angular что-то не выходит помогите разобраться.

app.component.html:

<div class="container master">
  <div class="row">
    <img src="../logo.png" alt="logo">
  </div>
  <div class="row col-xs-10">
    <input type="text"
           class="form-control"
           [(ngModel)]="queryString"
           placeholder="type phone number/name to find...">
  </div>
  <div class="row col-xs-12">
    <table class="table">
      <thead>
      <th>id</th>
      <th>number</th>
      <th>owner</th>
      </thead>
      <tbody>
      <tr *ngFor="let phone of phones | FilterPipe: queryString">
        <td>{{ phone.id }}</td>
        <td>{{ phone.number }}</td>
        <td>{{ phone.owner }}</td>
      </tr>
      </tbody>
    </table>
  </div>
</div>

app.component.ts:

import { Component } from '@angular/core';
import { FilterPipe } from './pipes';

export class Phone {
    id: string;
    number: string;
    owner: string;
}

const phoneList: Phone[] = [
    { id: 1, number: '200', owner: 'Соколов Николай' },
    { id: 2, number: '225', owner: 'Петров Петр' },
    { id: 3, number: '200', owner: 'Иванов Иван' }
];

@Component({
  selector: 'pb',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Phone Book';
  phones = phoneList;
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FilterPipe } from './pipes'

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    FilterPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

pipes.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
  transform(value: any, input: string) {
    if (input) {
      input = input.toLowerCase();
      return value.filter(function (el: any) {
        return el.toLowerCase().indexOf(input) > -1;
      })
    }
    return value;
  }
}

2 ответа 2

1

Пару замечаний по коду:

  1. Придерживайся строгой типизации. Например transform(value: Phone[], input: string) вместо transform(value: any, input: string), твоя бы ошибка определилась на этапе компиляции.
  2. Имена pipe делай в camelCase
  3. Для моделей лучше использовать interface чем class. Проще выполнять преобразование raw json.

export interface Phone { id?: string; number?: string; owner?: string; }

13
  • Спасибо, я только начал его изучать еще не все тонкости изучил) Подскажите, а как не выводить таблицу если не нашлось ничего из поиска, пробовал через *ngIf не вышло
    – noanother
    13 июн 2017 в 21:48
  • Напиши свой вариант кода 13 июн 2017 в 21:51
  • пробовал через else в pipe, но там не выйдет. вот так - <table class="table" *ngIf="queryString"> - выходит не совсем то, с пустой строкой ничего не показывает
    – noanother
    13 июн 2017 в 21:58
  • Во первых нужно заинжектить пайп в AppComponent, например как тут. во вторых обернуть вызов transform в метод компонента check(query: string):boolean { return this.filterPipe.transform(this.phoneList, query).length > 0}. И соответственно <table class="table" *ngIf="check(queryString)"> 13 июн 2017 в 22:06
  • заинжектить пайп в AppComponent - это не совсем понял
    – noanother
    13 июн 2017 в 22:09
0

Все оказалось проще:

export class FilterPipe implements PipeTransform {
  transform(value: any, input: string) {
    if (input) {
      input = input.toLowerCase();
      return value.filter(function (el: any) {
        if (el.number.toLowerCase().indexOf(input) > -1) {
          return el.number.toLowerCase().indexOf(input) > -1;
        }
        if (el.dep.toLowerCase().indexOf(input) > -1) {
          return el.dep.toLowerCase().indexOf(input) > -1;
        }
        if (el.owner.toLowerCase().indexOf(input) > -1) {
          return el.owner.toLowerCase().indexOf(input) > -1;
        }
      })
    }
    return value;
  }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.