Why Angular.orderBy shows no data in Page? - javascript

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.

Related

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

ERROR ReferenceError: $ is not defined at angular datatables [duplicate]

This question already has answers here:
JQuery - $ is not defined
(36 answers)
Closed 4 years ago.
I'm trying to add Paging and sorting to my table but I got this error , howerver I follow all the steps which listed here
http://l-lin.github.io/angular-datatables/#/getting-started.
I already check the previous problem but I did't work with me
I install all its dependencies
Here's the code of the component :-
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ProductService } from '../../service/product-service.service';
import { Subscription, Subject } from 'rxjs';
#Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit, OnDestroy {
products: any[];
filteredProducts: any[];
subscribtion: Subscription;
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
constructor(private productService: ProductService) {
this.subscribtion = productService.getAll().
// We take a copy of Products and Assigned to filteredProducts
subscribe(
products => {
this.filteredProducts = this.products = products;
this.dtTrigger.next();
}
);
}
ngOnInit() {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 5,
processing: true
};
}
filter(queryStr: string) {
// console.log(this.filteredProducts);
if (queryStr) {
this.filteredProducts = this.products.
filter(p => p.payload.val().title.toLowerCase().includes(queryStr.toLowerCase()));
} else {
this.filteredProducts = this.products;
}
}
ngOnDestroy(): void {
// to UnSubscribe
this.subscribtion.unsubscribe();
}
}
Here's the code of the the HTML :-
I follow also all the steps here
<p>
<a routerLink="/admin/products/new" class="btn btn-primary">New Product</a>
</p>
<p>
<input type="text"
#query
(keyup)="filter(query.value)"
placeholder="Search ..." class="form-control">
</p>
<table
datatable [dtOptions]="dtOptions"
[dtTrigger]="dtTrigger" class="table" >
<thead class="thead-dark">
<tr>
<th scope="col">Title</th>
<th scope="col">Price</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let product of filteredProducts">
<td>{{ product.payload.val().title }}</td>
<td>{{ product.payload.val().price }}</td>
<td>
<a [routerLink]="['/admin/products/', product.key]">Edit</a>
</td>
</tr>
</tbody>
</table>
$ not defined mostly means you are not including JQuery.
try adding: to your program
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
source

Not able to load data from JSON in Angular 2

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.

Retrive firestore documentId and add to html

I'm building my first Angular app and I'm trying to integrate firestore.
So far I was able to retrieve data from firestore and also log the id with snapshot but I'm not being able to bring it all together.
Is there a way to add the id to the client Model?
I was reading the angularfire2 documentation where it says that we can't use the $key property and now we should use snapshot but I can't figure it out.
Thanks
This is my Service
#Injectable()
export class ClientService {
clientsCollection: AngularFirestoreCollection<Client>;
clients: Observable<Client[]>;
snapshot: any;
constructor(private afs: AngularFirestore) {
this.clientsCollection = this.afs.collection('clients');
this.clients = this.clientsCollection.valueChanges();
// snapshot for id/metadata
this.snapshot = this.clientsCollection.snapshotChanges()
.map(arr => {
console.log(arr);
});
}
}
My client.component.ts
#Component({
selector: 'app-clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {
clients: Client[];
snapshots: any[];
constructor(
public clientService: ClientService
){}
ngOnInit(){
this.clientService.clients.subscribe(clients => {
this.clients = clients;
});
}
}
And my client.component.html
<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></td>
<td>{{ client.firstName }} {{ client.lastName }}</td>
<td>{{ client.email }}</td>
<td>{{ client.balance }}</td>
<td>Details</td>
</tr>
</tbody>
</table>
<ng-template #noClients>
<hr>
<h5>There are no clients in the system</h5>
</ng-template>
this is what I have so far
You can find answer in angularfire2 documents
export class AppComponent {
private shirtCollection: AngularFirestoreCollection<Shirt>;
shirts: Observable<ShirtId[]>;
constructor(private readonly afs: AngularFirestore) {
this.shirtCollection = afs.collection<Shirt>('shirts');
// .snapshotChanges() returns a DocumentChangeAction[], which contains
// a lot of information about "what happened" with each change. If you want to
// get the data and the id use the map operator.
this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
});
});
}
}
and this template
<ul>
<li *ngFor="let shirt of shirts | async">
{{ shirt.id }} is {{ shirt.price }}
</li>
</ul>

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