Why mt pagination is not working
export class AppComponent implements OnInit {
title = 'app';
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
#ViewChild(MatPaginator) paginator: MatPaginator;
ngOnInit() {
this.dataSource.paginator = this.paginator;
}
This is the same exaple which I copied from https://material.angular.io/components/table/overview
Related
I am fairly new to Angular and have been trying to make a date range filter on the createDate column for my Mat Table. When I hit the filter button, it just populates a blank table. The code for the filter is in the constructor and the datFil(). I have tried a few different things but to no avail. Any help would be greatly appreciated!
TypeScipt
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
import { MatSort} from '#angular/material/sort';
import {MatPaginator} from '#angular/material/paginator';
import {MatTableDataSource} from '#angular/material/table';
import { MatDialog, MatDialogConfig } from '#angular/material';
import { DialogDataComponent } from "../dialog-data/dialog-data.component";
import { DatePipe } from '#angular/common';
import {FormControl, FormGroup} from '#angular/forms';
export interface User {
id: number;
name: string;
distributor: string;
storeNum: number;
poNum: number;
createDate: Date;
recDate: Date;
totalUnits: number;
}
#Component({
selector: 'app-order-table',
templateUrl: './order-table.component.html',
styleUrls: ['./order-table.component.scss']
})
export class OrderTableComponent implements OnInit{
[x: string]: any;
public users: User[];
public begin: string;
public end: string;
private usersUrl = 'api/users';
// public doFilter = (value: string) => {
// console.log("testing: " + value);
// this.dataSource.filter = value.trim().toLocaleLowerCase();
// }
displayedColumns: string[] = ['name', 'distributor', 'storeNum', 'poNum', 'createDate', 'recDate', 'totalUnits'];
pipe: DatePipe;
dataSource = new MatTableDataSource<User>(this.users);
#ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
#ViewChild(MatSort, {static: true}) sort: MatSort;
storeFilter = new FormControl();
poFilter = new FormControl();
nameFilter = new FormControl();
dateFilter = new FormControl();
filteredValues = {
name: '', distributor: '', storeNum: '',
poNum: '', createDate: '', recDate: '', totalUnits: ''
};
constructor(private http: HttpClient, public dialog: MatDialog) {
this.dataSource.filterPredicate = (data, filter) =>{
if (this.begin && this.end) {
return data.createDate >= this.fromDate && data.createDate <= this.toDate;
}
return true;
}
};
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
ngOnInit() {
this.pipe = new DatePipe('en');
this.getUsers().subscribe(data => this.dataSource.data = data)
this.dataSource.paginator = this.paginator;
this.storeFilter.valueChanges.subscribe((storeFilterValue) => {
this.filteredValues['storeNum'] = storeFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.poFilter.valueChanges.subscribe((poFilterValue) => {
this.filteredValues['poNum'] = poFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.nameFilter.valueChanges.subscribe((nameFilterValue) => {
this.filteredValues['name'] = nameFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
});
this.dataSource.filterPredicate = this.customFilterPredicate();
console.log(this.dataSource);
}
dateFil(filter) {
console.log(this.begin);
console.log(this.end);
this.dataSource.filter = ''+Math.random();
}
HTML
<div>
<input matInput class="dateRange" (keypress)="keyPressNumbersDate($event)" [formControl]= "dateFilter" [(ngModel)]= "begin" placeholder="mm/dd/yyyy"> - <input matInput class="dateRange" (keypress)="keyPressNumbersDate($event)" [(ngModel)]= "end" placeholder="mm/dd/yyyy">
<button (click)= 'dateFil()'>Filter</button>
</div>
you can jus filter your datasource like this.
dateFil() {
dataSource = new MatTableDataSource<User>(this.users.filter(x=>x.createDate>=this.begin && x.createDate<=this.end));
}
I have created a demo you can find here
I want to refresh my webview when a button in the component is clicked.
I can't find a way to do so.
webview.components.ts code:
import {
...
}
#BasePage()
#Component({
selector: "ns-webview",
templateUrl: "./webview.component.html",
styleUrls: ["./webview.component.css"],
})
export class WebviewComponent implements AfterViewInit {
#ViewChild("webView", { static: false }) webView: ElementRef;
private noData: boolean = false;
private dataLoaded: boolean = false;
private schwellwerteLoaded: boolean = false;
public isLoading = true;
public graphPeriod = 1440;
oLangWebViewInterface;
constructor(
private uiService: UIService,
private dataService: DataService,
private authenticationService: AuthenticationService,
private route: ActivatedRoute,
private injector: Injector
) {}
ngAfterViewInit() {
setTimeout(() => {
this.isLoading = false;
}, 1000);
orientation.setOrientation("landscape");
this.setupWebViewInterface();
}
ngOnDestroy() {
console.log("destroy");
orientation.enableRotation();
}
onSubmit(period: number){
// let webView: WebView = this.webView.nativeElement;
let graphData = new GraphdataWrapper();
this.graphPeriod=1440;
this.graphPeriod= this.graphPeriod + period
console.log(this.graphPeriod)
this.load(graphData);
// this.webView.reload();
}
...
}
this.webview.reload is not working for whatever reason.
I have no clue why this is the case.
If you have any idea im glad to hear it.
Cheers!
You can just use the reload() method of the WebView
In your HTML file you will have something like this
<Button text="Refresh" (tap)="refresh()"></Label>
<WebView (loaded)="onWebViewLoaded($event)" src="https://www.google.com" ></WebView>
And then in your js/ts file you'll have something like
onWebViewLoaded(webargs) {
this.webview = webargs.object;
}
refresh() {
this.webview.reload();
}
I use angular 6, firebase and material angular. I can load my data into the table, I can sort them, have the paginator, and filter them globally
I would now like to modify my filter so that it just filters on the 'name' column and have a second filter field to filter on the 'common' column.
Can you help me on the strategy to adopt?
#Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss']
})
export class TableComponent implements OnInit {
showSpinner = true;
Data = {nom: '',finessgeo:'', cat1: '', commune: '',CP: '',departement:'',tel: ''}
displayedColumns = ['nom', 'finessgeo', 'cat1', 'commune', 'CP', 'departement', 'tel'];
dataSource = new MatTableDataSource();
applyFilter(filterValue: string) {
filterValue = filterValue.trim();
filterValue = filterValue.toLowerCase();
this.dataSource.filter = filterValue;
}
#ViewChild(MatPaginator) paginator: MatPaginator;
#ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
constructor(public authService: AuthService,private geoService: GeoService, private router: Router,private database: AngularFireDatabase) { }
onNewGeo() {
this.router.navigate(['']);
}
onSignOut() { this.authService.signOutUser(); }
ngOnInit() { return this.geoService.getGeos().subscribe(res =>{this.dataSource.data = res;this.showSpinner = false;}); }}
export class DataDataSource extends DataSource<any> {
constructor(private geoService: GeoService) { super() }
connect() {return this.geoService.getGeos();}
disconnect() {}
}
Try below code:
ngOnInit() {
this.dataSource.filterPredicate = function(data, filter: string): boolean {
return data.name.toLowerCase().includes(filter) || data.nom.toString() === filter;
};
}
I have a snackbar component which I have created like this!
import {Component, ViewEncapsulation, OnInit, OnDestroy} from '#angular/core';
import {
MatSnackBar,
MatSnackBarConfig,
MatSnackBarHorizontalPosition,
MatSnackBarVerticalPosition,
} from '#angular/material';
import { Subscription } from 'rxjs';
import { AuthenticationService } from "../../services/authentication.service";
#Component({
selector: 'snack-message',
templateUrl: './messages.component.html',
styleUrls: [ './mesaages.component.scss' ],
encapsulation: ViewEncapsulation.None
})
export class SnackBarMessages implements OnInit, OnDestroy {
action: boolean = true;
setAutoHide: boolean = true;
autoHide: number = 2000;
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
private showMessageSub: Subscription;
messageData: object;
addExtraClass: boolean = false;
constructor(public snackBar: MatSnackBar, public authenticationService: AuthenticationService) {
}
ngOnInit() {
this.messageData = this.authenticationService.getMessageData();
this.showMessageSub = this.authenticationService.getMessageListener()
.subscribe(data => {
this.messageData = data;
});
this.openMessageSnackBar(this.messageData);
}
openMessageSnackBar(data) {
let config = new MatSnackBarConfig();
config.verticalPosition = this.verticalPosition;
config.horizontalPosition = this.horizontalPosition;
config.duration = this.setAutoHide ? this.autoHide : 0;
this.snackBar.open(data.message, data.action, config);
}
ngOnDestroy() {
if (this.showMessageSub) {
this.showMessageSub.unsubscribe();
}
}
}
I have added subject and i have created a subscription which listens to the messageListener in my Authentication Service. Then i call next with my subjectListener with the data I want to pass. I am not getting any call on my component. I don't understand why ? This is my Service!
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Subject } from 'rxjs';
import { Router, ActivatedRoute } from '../../../node_modules/#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private mesageListener = new Subject<object>();
private messageData: object;
getMessageListener() {
return this.mesageListener.asObservable();
}
getMessageData() {
return this.messageData;
}
createUser(email: string, password: string) {
const userData: AuthModel = {
email: email,
password: password
}
const requestPath = this.getModes()[`${this.navigatedFrom}`];
this.http.post(`http://localhost:3000/api/${requestPath}/signup`,userData)
.subscribe(response => {
this.messageData = {
message: 'Sign Up Successful. Please Login now!',
action: 'Ok! Got it.'
}
this.mesageListener.next(this.messageData);
});
}
}
Try to use new BehaviorSubject<object>(null); for mesageListener .
you can see more details on Subject and BehavoiurSubject here : angular2-difference-between-a-behavior-subject-and-an-observable/
In Component subscribe to the value of Observable. It should work.
I got a ZF2 project with 2 Models PosTable/TopTable which extend AbstractTableGateway.
I want to Paginate results from those Tables so i have a Pagination function in both of them.
this is what the PosTable Model looks like:
...
class PosTable extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'pos';
$this->adapter = $adapter;
}
...
public function getPosPaginator($tid) {
$sql = $this->getSql();
$select = $sql->select();
$select->where('tid = '.$tid)->where('deleted = 0')->order('crdate ASC');
$adapter = new \Zend\Paginator\Adapter\DbSelect($select, $sql);
$paginator = new \Zend\Paginator\Paginator($adapter);
return $paginator;
}
...
which works perfectly.
but in my TopTable it looks the same like this:
...
class TopTable extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'top';
$this->adapter = $adapter;
}
public function getTopPaginator($fid) {
$sql = $this->getSql();
$select = $sql->select();
$select->where('fid = '.$fid)->where('deleted = 0');
$adapter = new \Zend\Paginator\Adapter\DbSelect($select, $sql);
$paginator = new \Zend\Paginator\Paginator($adapter);
return $paginator;
}
...
my controller looks like this for PosTable:
...
public function posAction(){
...
$pos = $this->getPosTable()->getPosPaginator($tid);
$pos->setCurrentPageNumber($pageid)->setItemCountPerPage(19);
... return $pos etc...
same controller topAction:
...
public function topAction(){
...
$top = $this->getTopTable()->getTopPaginator($fid);
$top->setCurrentPageNumber($pageid)->setItemCountPerPage(20);
...return $top etc..
in that controller i got also these functions:
public function getTopTable(){
return $this->getServiceLocator()->get('Application\Model\TopTable');
}
public function getPosTable(){
return $this->getServiceLocator()->get('Application\Model\PosTable');
}
PosTable Pagination works perfectly, but the TopTable Pagination doesnt work.
i get this error:
Fatal error: Call to a member function select() on a non-object in ....
seems like
$sql = $this->getSql();
doesnt return the object.
how can i solve this problem?
one works one doesnt for no obvious reason.
my module.php looks like this:
namespace Application;
class Module
{
public function getAutoloaderConfig()
{
return array('Zend\Loader\StandardAutoloader' =>
array('namespaces' =>
array(__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Model\TopTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Application\Model\TopTable($dbAdapter);
return $table;
},
'Application\Model\ForTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Application\Model\ForTable($dbAdapter);
return $table;
},
'Application\Model\PosTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Application\Model\PosTable($dbAdapter);
return $table;
},
),
);
}
}
Ok, after going through TableGateway Code and your extended class, I found the your implementation is not calling initialize which setup the sql object try to call the parent table gateway, below is the modified constructor for your PosTable and TopTable
/* for PosTable */
class PosTable extends TableGateway {
public function __construct($adapter) {
parent::__construct('pos', $adapter);
}
...
/* for TopTable */
class TopTable extends TableGateway {
public function __construct($adapter) {
parent::__construct('top', $adapter);
}
...