Not able to load data from JSON in Angular 2 - javascript

I'm working on loading data from JSON file in Angular 2.
This is my JSON file:
[
{
"processName": "SOUAD_1",
"processStatus": "Hibernating",
"UnprocessedCMSG": 123,
"TempackedCMSG": 10,
"DeferredCMSG": 32.99
},
{
"processName": "SOUAD_2",
"processStatus": "Hibernating",
"UnprocessedCMSG": 123,
"TempackedCMSG": 10,
"DeferredCMSG": 32.99
},
{
"processName": "SOUAD_3",
"processStatus": "Hibernating",
"UnprocessedCMSG": 123,
"TempackedCMSG": 10,
"DeferredCMSG": 32.99
}
]
This is my ts file where I specified the JSON path...
import {
Injectable
} from '#angular/core';
import {
Http,
Headers,
RequestOptions,
Response
} from '#angular/http';
import {
Observable,
Subject
} from 'rxjs/Rx';
import 'rxjs/Rx'; //get everything from Rx
import 'rxjs/add/operator/toPromise';
import {
IProduct
} from "../models/iproduct";
#Injectable()
export class ProcessJsonService {
private jsonFileURL: string = "../Data/jsonfile.json";
constructor(private http: Http) {}
//
getProcesslist(): Observable < IProduct[] > {
return this.http.get(this.jsonFileURL)
.map((response: Response) => <IProduct[]>response.json())
.catch(this.handleError);
}
private handleError(errorResponse: Response) {
console.log(errorResponse.statusText);
return Observable.throw(errorResponse.json().error || "Server error");
}
}
this is my my process-list-component.ts
import { Component, OnInit } from '#angular/core';
import { IProduct } from "../models/iproduct";
import {
Http
} from '#angular/http';
import {
ProcessJsonService
} from '../models/myjsonprocess';
import {
Observable
} from 'rxjs/Rx';
#Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
pageTitle: string = 'Product List';
imageWidth: number = 50;
imageMargin: number = 2;
showImage: boolean = false;
listFilter: string = '';
processList: IProduct[];
errorMessage: string;
constructor(private _processJsonService: ProcessJsonService) {
this.processList = [];
}
ngOnInit(): void {
let self = this;
self._processJsonService.getProcesslist().subscribe(response => this.processList = response, error => this.errorMessage = < any > error);
}
}
this is my process-list-component
<div class='panel panel-primary'>
<div class='panel-heading'>
{{pageTitle}}
</div>
<div class='panel-body'>
<div class='row'>
<div class='col-md-2'>Filter by:</div>
<div class='col-md-4'>
<input type='text' [(ngModel)]='listFilter' />
</div>
</div>
<div class='row'>
<div class='col-md-6'>
<h3>Filtered by: {{listFilter}} </h3>
</div>
</div>
<div class='table-responsive'>
<table class='table'
*ngIf='processList && processList.length'>
<thead>
<tr>
<th>Process Name</th>
<th>Process Status</th>
<th>Unprocessed CMSG</th>
<th>Tempacked CMSG</th>
<th>Deferred CMSG</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let process of processList">
<td>{{ process.processName }}</td>
<td>{{ process.processStatus | lowercase }}</td>
<td>{{ process.UnprocessedCMSG }}</td>
<td>{{ process.TempackedCMSG}}</td>
<td>{{ process.DeferredCMSG}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
I should get a table where the details of each process are shown. But, in the browser, I'm getting empty page, no data are shown.
Please, any help ??
This is what I'm getting in the console:
AppComponent.html:7 ERROR Error: StaticInjectorError(AppModule)[ProductListComponent -> ProcessJsonService]:
StaticInjectorError(Platform: core)[ProductListComponent -> ProcessJsonService]:
NullInjectorError: No provider for ProcessJsonService!
at _NullInjector.get (core.js:994)

Look at this code:
.subscribe(response => this.processList = response
And then in your template:
*ngFor="let process of processList | async"
You only use async pipe to retrieve values from an Observable/Promise. processList is neither of them, you already subscribed to the data and stored it in the variable, so just remove the async pipe from the template.

Related

Why Angular.orderBy shows no data in Page?

I am developing a Angular website with help of Firebase Firestore. It is my first project on Angular. I have learned Angular 2months ago. Please See the below codes: -
Component.html
<section class="rank">
<p class="records" *ngIf="members.length === 0">No Records Found.</p>
<div class="text-img" *ngIf="members.length > 0">
<p class="sb">Best Sulphuric</p>
<p class="role">Member</p>
<p class="name">
{{ members[0].payload.doc.data().name }}
</p>
</div>
<table *ngIf="members.length > 0">
<tr>
<th>ID</th>
<th>Name</th>
<th>Posts</th>
<th>Score</th>
</tr>
<tr *ngFor="let member of members; let indexOfelement = index">
<td>{{ indexOfelement + 1 }}</td>
<td>{{ member.payload.doc.data().name }}</td>
<td>{{ member.payload.doc.data().posts }}</td>
<td>{{ member.payload.doc.data().score }}</td>
</tr>
</table>
</section>
Component.ts
import { Component, OnInit } from '#angular/core';
import { AngularFirestore } from '#angular/fire/firestore';
#Component({
selector: 'app-rank',
templateUrl: './rank.component.html',
styleUrls: ['./rank.component.scss'],
})
export class RankComponent implements OnInit {
members: any;
constructor(public db: AngularFirestore) {
db.collection('members')
.snapshotChanges()
.subscribe((res) => (this.members = res));
}
ngOnInit(): void {}
}
When I open this on browser this shows all the data in members in Firestore. But when i change component.ts to this -->
Component.ts
import { Component, OnInit } from '#angular/core';
import { AngularFirestore } from '#angular/fire/firestore';
#Component({
selector: 'app-rank',
templateUrl: './rank.component.html',
styleUrls: ['./rank.component.scss'],
})
export class RankComponent implements OnInit {
members: any;
constructor(public db: AngularFirestore) {
this.members = db.collection('members').ref.orderBy('score');
}
ngOnInit(): void {}
}
It shows no data on window. Can you help me please?
Thanks in Advance for Helping.
In the second version,
You are missing the
.snapshotChanges()
.subscribe((res) => (this.members = res));
}
inside the constructor. Without the subscribe, Angular will not make any HTTP Requests and your component will not receive any data.

Cannot read property of undefined when calling method as a callback

I'm new to OOP and angular.
currently, I want to use reusable table with pagination that makes a request API if page change (pagination inside table component).
the problem is when I access my method using callback from table component (Child) I got undefined.
but when I try to move pagination to MasterGudang (Parent) Components it's work.
I don't really understand what's going on.
Error undefined
but here some code.
table.component.ts
import { Subject } from 'rxjs';
#Component({
selector: 'ngx-table-custom',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss']
})
export class TableComponent implements OnInit {
constructor() { }
#Input() items: any;
#Input() callback: any;
#Input() columns: [];
p: number = 1;
#ContentChild('action', { static: false }) actionRef: TemplateRef<any>;
ngOnInit(): void {
this.items = new Subject();
this.items.next();
}
onChangePage = (evt) => {
this.callback()
}
Gudang.component.ts
import { MasterGudangService } from '../../../../#core/services/master-service/menu-gudang/gudang/masterGudang.service';
#Component({
selector: "ngx-gudang",
templateUrl: './gudang.component.html',
styleUrls: ['./gudang.component.scss'],
})
#Injectable({
providedIn: 'root'
})
export class GudangComponent implements OnInit {
constructor(
public masterGudangService: MasterGudangService
) {
console.log(masterGudangService)
}
tableData: [];
isEdit: boolean = false;
currentPage: number = 1;
ngOnInit(): void {
this.getList();
}
getList (page?: number) {
this.masterGudangService.getPgb(page? page: this.currentPage).subscribe(response => {
const { data: { content, totalElements, size, number } } = response;
this.tableData = Object.assign({
data: content,
total: totalElements,
size: size,
number: number
});
});
}
}
And here I passing my function which is getList to table component
gudang.component.html
<ngx-table-custom [callback]="getList" [columns]="column" [items]="tableData">
<ng-template let-item #action>
<div class="row">
<button nbButton status="success" (click)="open(dialog, item, true)" class="mx-2" size="tiny"><nb-icon icon="edit"></nb-icon></button>
<button nbButton status="danger" (click)="onDelete(item)" size="tiny"><nb-icon icon="trash"></nb-icon></button>
</div>
</ng-template>
</ngx-table-custom>
MasterGudangService.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class MasterGudangService {
constructor(private http: HttpClient) { }
getPgb (page: number = 1, perPage: number = 10) :any {
return this.http.get(`my-api-url/pgb?page=${page}&size=${perPage}`)
}
}
table.component.html
<div class="row">
<div class="col-12">
<table class="table table-md table-striped">
<thead>
<tr style="background-color: #3366ff; color: #fff;">
<th *ngFor="let column of columns" class="text-basic">{{ column.value }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items.data | paginate: { itemsPerPage: 10, currentPage: p, totalItems: items.total }; index as idx;">
<td *ngFor="let column of columns">
<div *ngIf="column.key === 'number';"><b class="text-basic">{{ idx + 1 }}</b></div>
<div *ngIf="column.key !== 'action' && !isNested(column.key);" class="text-basic">{{ item[column.key] }}</div>
<div *ngIf="isNested(column.key);" class="text-basic">{{ getKeys(item, column.key) }}</div>
<!-- <div *ngIf="column.key === 'action; action_container"></div> -->
<ng-template [ngIf]="column.key === 'action'" #action_content>
<ng-container
*ngIf="actionRef"
[ngTemplateOutlet]="actionRef"
[ngTemplateOutletContext]="{$implicit:item}">
</ng-container>
</ng-template>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-12" align="center">
<pagination-controls (pageChange)="onChangePage($event)"></pagination-controls>
</div>
</div>
The context of Gudang.component.ts will not be available using callback from table component.
The proper way to implement should be passing the event instead of passing function for callback
table.component.ts
#Output() pageChange = new EventEmitter()
onChangePage = (evt) => {
this.pageChange.emit(evt);
}
gudang.component.html
<ngx-table-custom (pageChange)="getList($event)" [columns]="column" [items]="tableData">
...
</ngx-table-custom>
based on the error, it seems like masterGudangService is null at the time you are trying to access it. Adding this code might help you eliminate the error and at least debug what is going on and get a step further.
ngOnInit(): void {
if(this.masterGudangService)
this.getList();
else
console.log('service not defined!');
}
You could define a helper Method in GudangComponent
getListCallback() {
return this.getList.bind(this);
}
and use it here
<ngx-table-custom [callback]="getListCallback()" [columns]="column" [items]="tableData">

Why do I need to refresh the web page sometimes to see the data i retrieved from the api appear on my table? Angular 9

I created an API using asp.net and I used angular as my front end. I am able to get the data just fine but sometimes I would need to refresh the page once or a few more times in order to actually see the data on my table. I have absolutely no idea why this might be happening. I hope the code I have inserted below will be enough to find the solution to my problem
Here is typescript file of my table component
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import {DataService} from 'src/app/Services/data.service';
import {Anime} from 'src/app/Classes/anime';
import { NgModule } from '#angular/core';
import {MatDialog, MatDialogConfig } from '#angular/material/dialog';
import { DialogComponent } from 'src/app/dialog/dialog.component';
#Component({
selector: 'app-anime-table',
templateUrl: './anime-table.component.html',
styleUrls: ['./anime-table.component.css']
})
export class AnimeTableComponent implements OnInit {
AnimeArray : Anime[] = [] ;
data = false;
constructor(private router : Router,
private dataService : DataService,
private Dialog: MatDialog
) {}
ngOnInit(){
this.dataService.GetAnime()
.subscribe(data => data.forEach(element => {
var anime = new Anime();
anime.AnimeID = element.AnimeID;
anime.AnimeName = element.AnimeName;
anime.Anime_Description = element.Anime_Description;
this.AnimeArray.push(anime);
}))
}// ngOnInit
}//Export
Below is the html stuff
<br />
<button routerLink="/Dashboard" class="btn btn-primary">Go Home</button>
<button
routerLink="/CreateAnime"
class="btn btn-success"
style="margin-left: 15px;"
>
Add new Anime
</button>
<br />
<br />
<table class="table table-striped">
<thead>
<tr>
<th>Anime ID</th>
<th>Anime Name</th>
<th>Anime Description</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let anime of AnimeArray">
<td>{{ anime.AnimeID }}</td>
<td>{{ anime.AnimeName }}</td>
<td>{{ anime.Anime_Description }}</td>
<td>
<!-- <a [routerLink] = "['/Anime']" [queryParams] = "anime.AnimeID" class="btn btn-success"> Edit </a> -->
<button (click)="EditAnime(anime.AnimeID)" class="btn btn-success">
Edit
</button>
<button
(click)="DeleteAnime(anime.AnimeID, anime.AnimeName)"
style="margin-left: 15px;"
class="btn btn-danger"
>
Delete
</button>
</td>
</tr>
</tbody>
</table>
Here is a piece of the dataservice that gets the Anime information from the API i created.
import { Injectable } from '#angular/core';
import {HttpClient} from '#angular/common/http'
import {HttpHeaders} from '#angular/common/http';
import { from, Observable } from 'rxjs';
import {Anime} from '../Classes/anime';
#Injectable({
providedIn: 'root'
})
export class DataService {
url : string;
header : any;
option : any;
constructor(private http : HttpClient) {
this.url = 'http://localhost:50484/api/Values/';
const headerSettings: {[name: string]: string | string[]; } = {};
//this.header = new HttpHeaders(headerSettings);
this.header = {'Authorization' : 'bearer ' + localStorage.getItem('UserToken')}
let headers = new HttpHeaders({'Authorization' : 'bearer ' + localStorage.getItem('UserToken')})
this.option = {headers : headers};
}
GetAnime() : Observable<Anime[]> {
console.log(this.header);
const headers = {'Authorization' : 'bearer ' + localStorage.getItem('UserToken')}
return this.http.get<Anime[]>(this.url + 'GetAllAnime/' , {headers});
}
} // data service
P.S I am currently not seeing any errors in the browser console, the cmd or in visual studio code
Try map data first and replace the entire array, instead of pushing in the array.
ngOnInit() {
this.dataService.GetAnime().subscribe(data => data =>
(this.AnimeArray = data.map(element => {
var anime = new Anime();
anime.AnimeID = element.AnimeID;
anime.AnimeName = element.AnimeName;
anime.Anime_Description = element.Anime_Description;
return anime;
}))
);
} // ngOnInit

Angular firebase not show the Key

I want To show the $key of client from firebasedatabase which also called uniquekey maybe like
-Kdl_wRRkn7njxgz4B54
i try but it dont show the key but show the other data in key
also try to replace $key with key dont work . i know it need change in code if any one can thanks :)
client.html
<div class="row">
<div class="col-md-6">
<h2><i class="fa fa-users"></i> Clients</h2>
</div>
<div class="col-md-6">
<h5 class="pull-right text-muted">Total Owed: {{totalOwed | currency:"USD":true}}</h5>
</div>
</div>
<table *ngIf="clients?.length > 0;else noClients" class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Balance</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let client of clients">
<td>{{client.$key}}</td>
<td>{{client.firstName}} {{client.lastName}}</td>
<td>{{client.email}}</td>
<td>{{client.balance | currency:"USD":true}}</td>
<td><a [routerLink]="['/client/'+client.$key]" href="" class="btn btn-secondary btn-sm"><i class="fa fa-arrow-circle-o-right"></i> Details</a></td>
</tr>
</tbody>
</table>
<ng-template #noClients>
<hr>
<h5>There are no clients in the system</h5>
</ng-template>
client.ts
import { Component, OnInit } from '#angular/core';
import { ClientService } from '../../services/client.service';
import { Client } from '../../models/Client';
#Component({
selector: 'app-clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {
clients:any[];
totalOwed:number;
constructor(
public clientService:ClientService
) { }
ngOnInit() {
this.clientService.getClients().valueChanges().subscribe(clients => {
this.clients = clients;
this.getTotalOwed();
});
}
getTotalOwed(){
let total = 0;
for(let i = 0;i < this.clients.length;i++){
total += parseFloat(this.clients[i].balance);
}
this.totalOwed = total;
console.log(this.totalOwed);
}
}
client.service.ts
import { Injectable } from '#angular/core';
import { AngularFireDatabase} from 'angularfire2/database';
import { AngularFireObject, AngularFireList } from 'angularfire2/database';
import { Observable } from 'rxjs';
import { Client } from '../models/Client';
#Injectable()
export class ClientService {
clients: AngularFireList<any>;
client: AngularFireObject<any>;
constructor(
public af:AngularFireDatabase
) {
this.clients = this.af.list('/clients') as AngularFireList<Client[]>;
}
getClients(){
return this.clients;
}
newClient(client:Client){
this.clients.push(client);
}
getClient(id:string){
this.client = this.af.object('/clients/'+id) as AngularFireObject<Client>;
return this.client;
}
}
Use snapshotChanges().map() to store the key:
constructor(
public af:AngularFireDatabase
) {
this.clientsRef = this.af.list('/clients') as AngularFireList<Client[]>;
this.clients = this.clientsRef.snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
)
);
}
Then you should be able to access it as normal:
<td>{{client.key}}</td>

Angular 4 Filter Search Custom Pipe

So I am trying to build a custom pipe to do a search filter of multiple values in a ngFor loop. I have looked for a number of hours for a good working example, and most of them are based on previous builds and don't seem to work. So I was building the Pipe and using the console to give me the values. However, I cannot seem to get the input text to show up.
Here are the previous places I have looked to find working examples:
Angular 4 Pipe Filter
http://jilles.me/ng-filter-in-angular2-pipes/
https://mytechnetknowhows.wordpress.com/2017/02/18/angular-2-pipes-passing-multiple-filters-to-pipes/
https://plnkr.co/edit/vRvnNUULmBpkbLUYk4uw?p=preview
https://www.youtube.com/results?search_query=filter+search+angular+2
https://www.youtube.com/watch?v=UgMhQpkjCFg
Here is the code that I currently have:
component.html
<input type="text" class="form-control" placeholder="Search" ngModel="query" id="listSearch" #LockFilter>
<div class="panel panel-default col-xs-12 col-sm-11" *ngFor="let lock of locked | LockFilter: query">
<input type="checkbox" ngModel="lock.checked" (change)="openModal($event, lock)" class="check" id="{{lock.ID}}">
<label for="{{lock.ID}}" class="check-label"></label>
<h3 class="card-text name" ngModel="lock.name">{{lock.User}}</h3>
<h3 class="card-text auth" ngModel="lock.auth">{{lock.AuthID}}</h3>
<h3 class="card-text form" ngModel="lock.form">{{lock.FormName}}</h3>
<h3 class="card-text win" ngModel="lock.win">{{lock.WinHandle}}</h3>
</div>
pipe.ts
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'LockFilter'
})
export class LockFilterPipe implements PipeTransform {
transform(locked: any, query: string): any {
console.log(locked); //this shows in the console
console.log(query); //this does not show anything in the console when typing
if(!query) {
return locked;
}
return locked.filter((lock) => {
return lock.User.toLowerCase().match(query.toLowerCase());
});
}
}
I have imported the pipe into the module.
I am still a little newer to Angular 4 and am trying to figure out how to make this work. Anyways thanks for your help!
I guess I will need to be more specific. I already built out a filter search in JS that does not filter all of the options, which is what I am trying to do. Not just filter the User Name. I am filtering all 4 pieces of data. I chose a Pipe as this was what Angular suggests you do as they originally used them in AngularJS. I am just trying to essentially recreate the filter pipe we had in AngularJS that they removed for performance. All options I have found don't work, or are from previous builds of Angular.
If you need anything else from my code let me know.
I have to implement search functionality in my local and Here is Updated your code. please do this way.
Here is the code that I have to update.
directory Structure
app/
_pipe/
search/
search.pipe.ts
search.pipe.spec.ts
app/
app.component.css
app.component.html
app.component.ts
app.module.ts
app.component.spec.ts
command run for creating pipe
ng g pipe search
component.html
<input type="text" class="form-control" placeholder="Search" [(ngModel)]="query" id="listSearch">
<div class="panel panel-default col-xs-12 col-sm-11" *ngFor="let lock of locked | LockFilter: query">
<input type="checkbox" (change)="openModal($event, lock)" class="check" id="{{lock.ID}}">
<label [for]="lock.ID" class="check-label"></label>
<h3 class="card-text name">{{lock.User}}</h3>
<h3 class="card-text auth">{{lock.AuthID}}</h3>
<h3 class="card-text form">{{lock.FormName}}</h3>
<h3 class="card-text win">{{lock.WinHandle}}</h3>
</div>
component.js
Note: In this file, i have to use dummy records for implementation and testing purpose.
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
public search:any = '';
locked: any[] = [];
constructor(){}
ngOnInit(){
this.locked = [
{ID: 1, User: 'Agustin', AuthID: '68114', FormName: 'Fellman', WinHandle: 'Oak Way'},
{ID: 2, User: 'Alden', AuthID: '98101', FormName: 'Raccoon Run', WinHandle: 'Newsome'},
{ID: 3, User: 'Ramon', AuthID: '28586', FormName: 'Yorkshire Circle', WinHandle: 'Dennis'},
{ID: 4, User: 'Elbert', AuthID: '91775', FormName: 'Lee', WinHandle: 'Middleville Road'},
]
}
}
module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { SearchPipe } from './_pipe/search/search.pipe';
#NgModule({
declarations: [
AppComponent,
SearchPipe
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
pipe.ts
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'LockFilter'
})
export class SearchPipe implements PipeTransform {
transform(value: any, args?: any): any {
if(!value)return null;
if(!args)return value;
args = args.toLowerCase();
return value.filter(function(item){
return JSON.stringify(item).toLowerCase().includes(args);
});
}
}
I hope you are getting the pipe functionality and this will help you.
Simple filterPipe for Angular 2+
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filter'
})
export class filterPipe implements PipeTransform {
transform(items: any[], field:string, value: string): any[] {
if(!items) return [];
if(!value) return items;
return items.filter( str => {
return str[field].toLowerCase().includes(value.toLowerCase());
});
}
}
Here is the HTML
<input type="text" class="form-control" placeholder="Search" id="listSearch" #search>
<div class="panel panel-default col-xs-12 col-sm-11" *ngFor="let lock of locked | filter:'propName': search.value>
<input type="checkbox" (change)="openModal($event, lock)" class="check" id="{{lock.ID}}">
<label [for]="lock.ID" class="check-label"></label>
<h3 class="card-text name">{{lock.User}}</h3>
<h3 class="card-text auth">{{lock.AuthID}}</h3>
<h3 class="card-text form">{{lock.FormName}}</h3>
<h3 class="card-text win">{{lock.WinHandle}}</h3>
</div>
in HTML PropName is dummy text. In place of PropName use your any object property key.
Follow this code to filter specific column instead of all columns in table using custom filters
filename.component.html
<table class="table table-striped">
<thead>
<tr>
<th scope="col">product name </th>
<th scope="col">product price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let respObj of data | filter:searchText">
<td>{{respObj.product_name}}</td>
<td>{{respObj.product_price}}</td>
</tr>
</tbody>
</table>
filename.component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-productlist',
templateUrl: './productlist.component.html',
styleUrls: ['./productlist.component.css']
})
export class ProductlistComponent implements OnInit {
searchText: string;
constructor(private http: HttpClient) { }
data: any;
ngOnInit() {
this.http.get(url)
.subscribe(
resp => {
this.data = resp;
}
)
}
}
filename.pipe.ts
Create a class and implement it with PipeTransform, in that way we can write custom filter with transform method.
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filter'
})
export class PipeList implements PipeTransform {
transform(value: any, args?: any): any {
if(!args)
return value;
return value.filter(
item => item.product_name.toLowerCase().indexOf(args.toLowerCase()) > -1
);
}
}
Here is simple explanation to create custom pipe..as available pipes does not support it.
I found this solution here..Nicely explained it
Create pipe file advanced-filter.pipe
import {Pipe, PipeTransform} from '#angular/core';
#Pipe({
name: 'advancedFilters'
})
export class AdvancedFilterPipe implements PipeTransform {
transform(array: any[], ...args): any {
if (array == null) {
return null;
}
return array.filter(function(obj) {
if (args[1]) {
return obj.status === args[0];
}
return array;
});
}
}
Here, array – will be data array passed to your custom pipe
obj – will be the object of data by using that object you can add condition to filter data
We have added condition obj.status === args[0] so that data will get filter on status which is passed in .html file
Now, import and declare custom pipe in module.ts file of component:
import {AdvancedFilterPipe} from './basic-filter.pipe';
//Declare pipe
#NgModule({
imports: [DataTableModule, HttpModule, CommonModule, FormsModule, ChartModule, RouterModule],
declarations: [ DashboardComponent, AdvancedFilterPipe],
exports: [ DashboardComponent ],
providers: [{provide: HighchartsStatic}]
})
Use of created custom angular pipe in .html file
<table class="table table-bordered" [mfData]="data | advancedFilters: status" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy" [(mfSortOrder)]="sortOrder">
<thead>
<tr>
<th class="sortable-column" width="12%">
<mfDefaultSorter by="inquiry_originator">Origin</mfDefaultSorter>
</th>
</tr>
</thead>
<tbody class="dashboard-grid">
<ng-container *ngFor="let item of mf.data; let counter = index;">
<tr class="data-row {{ item.status }} grid-panel-class-{{ counter }}">
<td class="align-center">{{ item.trn_date }}</td>
<td>{{ item.trn_ref }}</td>
</tr>
</tbody>
</table>
//If you are using *ngFor and want to use custom angular pipe then below is code
<li *ngFor="let num of (numbers | advancedFilters: status">
{{ num | ordinal }}
</li>
A simple Java-like logic that I could think of which might not look very compact in terms of typescript, is as below:
transform(value:IBook[], keyword:string) {
if(!keyword)
return value;
let filteredValues:any=[];
for(let i=0;i<value.length;i++){
if(value[i].name.toLowerCase().includes(keyword.toLowerCase())){
filteredValues.push(value[i]);
}
}
return filteredValues;
}
<h2>Available Books</h2>
<input type="text" [(ngModel)]="bookName"/>
<ul class="books">
<li *ngFor="let book of books | search:bookName"
[class.selected]="book === selectedBook"
(click)="onSelect(book)">
<span class="badge">{{book.name}}</span>
</li>
</ul>
You can use the given function instead on the (input) event of your input box
filterNames(event)
{
this.names_list = this.names_list.filter(function(tag) {
return tag.name.toLowerCase().indexOf(event.target.value.toLowerCase()) >= 0;
});
}
Hope it helps..

Categories