Implementing Input Filtering in Angular 2

How can I create a custom @Pipe to filter data in a table using an input tag?

<tr *ngFor='let list of lists'>
      <td><input type="" name="" value=""></td>
      <td>{{ list.name }}</td>
      <td>{{ list.location }}</td>
      <td>{{ list.type_id }}</td>
    <tr>

I retrieve the data from an API using HTTP service:

getServices(): Observable<any> {
        return this._http.get(this._url)
            .map(res => res.json());
    }

UPDATE:

Here is my service component:

import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';

import 'rxjs/add/operator/map'

@Injectable() 
export class TableComponentService{
    private _url = 'http://101.496.222.511:8080/api/v1/10';

    constructor(private _http: Http) {

    }

    names:string[];
    getServices(): Observable<any> {
        return this._http.get(this._url)
            .map(res => res.json());
    }

}

And here is the table component:

import { Component, OnInit } from '@angular/core';
import { TableComponentService } from './table.service';

@Component({
    selector: 'tablecomponent',
    templateUrl: 'app/table.template.html',
    providers: [TableComponentService]
})
export class TableComponent implements OnInit {
    lists: any[];

    constructor(private _service: TableComponentService) {

    }

    ngOnInit() {
        this._service.getServices()
            .subscribe(lists => this.lists = lists)
    }

}

Answer №1

One way to improve your code is to use the keyup event instead of pipe for calling the getServices() function. This will allow you to store the value received in a variable and display the result wherever needed using that variable.

For example:


 <tr *ngFor='let list of lists'>
      <td><input type="" name="" value="" (keyup)="getServices()" >
       <span *ngFor='let name of names'>{{name }}</span>
      </td>
      <td>{{ list.name }}</td>
      <td>{{ list.location }}</td>
      <td>{{ list.type_id }}</td>
 <tr>

names:string[];
getServices(): Observable<any> {
    this.names=this._http.get(this._url)
        .map(res => res.json());
}

EDIT:-

To make _service public in constructor, do the following:

constructor(public_service: TableComponentService)

Then in the html:

<input type="" name="" value="" (keyup)="_service.getServices()" >

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Primeng table: row grouping width does not work properly when scrollable is enabled

Currently, I am implementing a Primeng table within an Angular project. Below is the code snippet showcasing how the table is being utilized: <p-table [value]="cars" dataKey="brand" [scrollable]="'true'" scrollHeight="400px"> <ng-te ...

Display Bootstrap Modal using Typescript in Angular

Looking for some creative ideas here... My Angular site allows users to register for events by filling out a form. They can also register themselves and other people at the same time. https://i.sstatic.net/a44I7.png The current issue ~ when a user clicks ...

Tracking page visits in an Angular single page application with Sitecore using Beacon.js

Currently, I am looking for a way to track every page visit within my Angular single page application using Sitecore (Beacon.js). Despite adding a line to my index.html file, the page visit is only being logged once and not for every component visit. Is th ...

The inner workings of Angular 2: uncovering what occurs once we navigate to http://localhost:4200 on our browser

Could anyone provide a detailed explanation of the startup process for an Angular2 project? For example, after creating a sample project using Angular CLI: Run 'ng new my-test-app' Navigate to 'cd my-test-app' Start the server with & ...

Steps for adding an array of JSON objects into a single JSON object

I have a JSON array that looks like this: var finalResponse2 = [ {Transaction Amount: {type: "number"}}, {UTR number: {type: "string"}} ] My goal is to convert it into the following format: responses : [ { Transaction Amount: {type: "number"}, UTR numbe ...

What causes the error message "Expected ':' when utilizing null conditional in TypeScript?"

UPDATE: After receiving CodeCaster's comment, I realized the issue was due to me using TypeScript version 3.5 instead of 3.7+. It was surprising because these checks seemed to be working fine with other Angular elements, such as <div *ngIf="pa ...

Identified the category

How can I retrieve the default option from a list of options? type export type Unpacked<T> = T extends Array<infer U> ? U : T; interface getDefaultValue?: <T extends Option[]>(options: T) => Unpacked<T>; Example const options = ...

Access the file in response to the angular2 message

Forgive my ignorance, but I'm curious to know how to effectively prompt the user to download a file sent by the backend through the response. Can anyone shed some light on this? ...

Customize the appearance of checkboxes within a mat-select that contains multiple options

Currently, I have a mat-select element integrated with the multiple option (you can check out an example from the documentation here). My objective is to customize the color of the checkboxes when they are selected since their default color is blue. He ...

Validator using asynchronous methods in Angular 2

Currently, I am in the process of incorporating asynchronous custom validation into my project. Below is the structure of my validation class: export class CustomValidators{ _auth_service; constructor(auth_service:AuthService){ this._auth_service = au ...

API response containing JSON data is not being displayed properly in the webdatarocks angular component

I can't seem to figure out how to properly display the JSON formatted data returned by a REST API using Angular. Any suggestions on how to accomplish this? Here's what I've been attempting to do - fetchData() { this.service.fetchData().s ...

The 'get' property in the class 'ToastInjector' cannot be assigned to the 'get' property in its base class 'Injector'

error TS2416: The property 'get' in the type 'ToastInjector' cannot be assigned to the same property in the base type 'Injector'. The type '(token: any, notFoundValue?: T, flags?: InjectFlags) => ToastPackage | T&apos ...

Arrange photos in a grid using React Dropzone uploaders

I'm having trouble figuring out how to create a custom preview similar to an image set in a grid using the react-dropzone-uploader component for uploading multiple files. Currently, when I upload images, they are displayed as shown in my normal uploa ...

Errors related to missing RxJS operators are occurring in the browser, but are not showing up in Visual Studio

Recently, I encountered a peculiar problem with my Angular4 project, which is managed under Angular-CLI and utilizes the RxJS library. Upon updating the RxJS library to version 5.5.2, the project started experiencing issues with Observable operators. The s ...

Exploring the Functionality of Algolia Places within a Next.js Application

Currently, I am working on integrating the Algolia Places functionality into my next.js project using TypeScript. To begin, I executed npm install places.js --save Next, I inserted <input type="search" id="address-input" placeholder ...

Utilize generic typings to interact with the Array object

I'm facing a challenge in developing an interface that is dependent on another interface. Everything was going smoothly until I reached the Array of Objects. Let me elaborate, I have an 'Entity' that defines how a document is stored in a ...

Show the Array List in a left-to-right format

Is there a way to display an array list from left to right with a div scroll, instead of top to bottom? I am having trouble achieving this. Here is my demo code for reference. HTML <div> <h2 class="ylet-primary-500 alignleft">Sessions</h ...

Tips for making a dynamic link button using Angular

I am currently working on creating responsive buttons that will navigate to specific pages using Angular routing. Here is my routing configuration: const routes: Routes = [ { path: 'home', component: HomeComponent}, { path: ' ...

Experience the ease of using drag and drop functionality with Angular's ng2-dragula feature

I'm currently implementing drag and drop functionality with ng2-dragula. While I've been able to successfully drag and drop, things have become a bit complicated due to the project requirements. My goal is to dynamically add disciplines to a mou ...

The explanation of the Angular tutorial is not displayed correctly

Hi there! I was working on a tutorial in Angular about using geofire location queries with Google Maps. It was quite interesting and I followed all the instructions provided in this video tutorial: . However, when I completed the project and ran it, I ende ...