如何解决带有自定义过滤器方法 mat-select 的 Angular Material Table 自己的数据源
我正在尝试在材料数据表中使用自定义过滤器。我有一个下拉列表,需要获取具有选定下拉列表值的列。
编码我的数据源
export class AllstaffComponent implements OnInit {
displayedColumns = [
'select','name','designation','mobile','email','date','address','status','actions',];
flter: Filter[] = [
{id: 0,value: 'Active'},{id: -1,value: 'All'},{id: 1,value: 'Modified'},{id: 2,value: 'Deleted'}
];
exampleDatabase: StaffService | null;
dataSource: ExampleDataSource | null;
selection = new SelectionModel<Staff>(true,[]);
id: number;
staff: Staff | null;
isTblLoading = true;
changestatus: FormGroup;
sourceFilter: FormGroup;
public Mystatus = '';
constructor(
public httpClient: HttpClient,public dialog: MatDialog,public staffService: StaffService,private snackBar: MatSnackBar,private fb: FormBuilder,private router: Router,) {
this.changestatus = this.fb.group({
status: ['',[Validators.required]]
});
this.sourceFilter = this.fb.group({
ss: ['',[Validators.required]]
});[enter image description here][1]
}
@ViewChild('status',{ static: true }) status: ElementRef;
@ViewChild(MatPaginator,{ static: true }) paginator: MatPaginator;
@ViewChild(MatSort,{ static: true }) sort: MatSort;
@ViewChild('filter',{ static: true }) filter: ElementRef;
@ViewChild(MatMenuTrigger)
contextMenu: MatMenuTrigger;
contextMenuPosition = { x: '0px',y: '0px' };
ngOnInit() {
this.loadData();
// console.log(this.exampleDatabase.Filter);
}
StatusSelected(){
const dfilter = this.sourceFilter.get('ss').value;
this.Mystatus = dfilter === null ? '' : dfilter;
// // create string of our searching values and split if by '$'
// this.dataSource.status=value;
// console.log('value get'+this.dataSource.status);
// fromEvent(this.status.nativeElement,'selectionChange').subscribe(() => {
// if (!this.dataSource) {
// return;
// }
// this.dataSource.status = value;
// console.log(this.dataSource.status);
// });
// const selectObs$ = fromEvent(this.status.nativeElement,'selectionChange');
// console.log('Meta Signal Changed to ' + this.selectedMetaSignal.nativeElement.value);
}
handleMetaSignalChange() {
// // Now selectedMetaSignal is a MatOption,not a native Element
// this.dataSource.status=this.selectedMetaSignal.value
// console.log('Meta Signal Changed to ' + this.selectedMetaSignal.value);
}
refresh() {
this.loadData();
}
addNew() {
const dialogRef = this.dialog.open(FormDialogComponent,{
data: {
staff: this.staff,action: 'add',},});
dialogRef.afterClosed().subscribe((result) => {
if (result === 1) {
// After dialog is closed we're doing frontend updates
// For add we're just pushing a new row inside DataService
this.exampleDatabase.dataChange.value.unshift(
this.staffService.getDialogData()
);
this.refreshTable();
this.showNotification(
'snackbar-success','Add Record Successfully...!!!','bottom','center'
);
}
});
}
editCall(row) {
// console.log(row.id)
this.id = row.id;
const dialogRef = this.dialog.open(FormDialogComponent,{
data: {
staff: row,action: 'edit',});
dialogRef.afterClosed().subscribe((result) => {
if (result === 1) {
// When using an edit things are little different,firstly we find record inside DataService by id
const foundindex = this.exampleDatabase.dataChange.value.findindex(
(x) => x.id === this.id
);
// Then you update that record using data from dialogData (values you enetered)
this.exampleDatabase.dataChange.value[
foundindex
] = this.staffService.getDialogData();
// And lastly refresh table
this.refreshTable();
this.showNotification(
'black','Edit Record Successfully...!!!','center'
);
}
});
}
Details(row) {
this.staffService.addItem(row);
this.router.navigate(['/admin/staff/about-staff'],{queryParams: { id: row.userId } });
}
deleteItem(row) {
// console.log(row);
this.id = row.id;
const dialogRef = this.dialog.open(DeleteDialogComponent,{
data: row,});
dialogRef.afterClosed().subscribe((result) => {
if (result === 1) {
const foundindex = this.exampleDatabase.dataChange.value.findindex(
(x) => x.id === this.id
);
// for delete we use splice in order to remove single object from DataService
this.exampleDatabase.dataChange.value.splice(foundindex,1);
this.refreshTable();
this.showNotification(
'snackbar-danger','Delete Record Successfully...!!!','center'
);
}
});
}
private refreshTable() {
this.paginator._changePageSize(this.paginator.pageSize);
}
/** Whether the number of selected elements matches the total number of rows. */
isAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.renderedData.length;
return numSelected === numRows;
}
/** Selects all rows if they are not all selected; otherwise clear selection. */
masterToggle() {
this.isAllSelected()
? this.selection.clear()
: this.dataSource.renderedData.forEach((row) =>
this.selection.select(row)
);
}
removeSelectedRows() {
const totalSelect = this.selection.selected.length;
this.selection.selected.forEach((item) => {
// console.log(item.userId);
const index: number = this.dataSource.renderedData.findindex(
(d) => d === item,// console.log(item.userId),this.staffService.delete(item.userId)
);
// console.log(this.dataSource.renderedData.findindex((d) => d === item));
this.exampleDatabase.dataChange.value.splice(index,1);
this.refreshTable();
this.selection = new SelectionModel<Staff>(true,[]);
});
this.showNotification(
'snackbar-danger',totalSelect + ' Record Delete Successfully...!!!','center'
);
}
public loadData() {
this.exampleDatabase = new StaffService(this.httpClient);
this.dataSource = new ExampleDataSource(
this.exampleDatabase,this.paginator,this.sort,// console.log(exampleDatabase),);
fromEvent(this.filter.nativeElement,'keyup').subscribe(() => {
if (!this.dataSource) {
return;
}
this.dataSource.filter = this.filter.nativeElement.value;
});
}
public DeletedList() {
this.exampleDatabase = new StaffService(this.httpClient);
this.dataSource = new ExampleDataSource(
this.exampleDatabase,'keyup').subscribe(() => {
if (!this.dataSource) {
return;
}
this.dataSource.filter = this.filter.nativeElement.value;
});
}
showNotification(colorName,text,placementFrom,placementAlign) {
this.snackBar.open(text,'',{
duration: 2000,verticalPosition: placementFrom,horizontalPosition: placementAlign,panelClass: colorName,});
}
// context menu
onContextMenu(event: MouseEvent,item: Staff) {
event.preventDefault();
this.contextMenuPosition.x = event.clientX + 'px';
this.contextMenuPosition.y = event.clientY + 'px';
this.contextMenu.menuData = { item: item };
this.contextMenu.menu.focusFirstItem('mouse');
this.contextMenu.openMenu();
}
}
export class ExampleDataSource extends DataSource<Staff> {
private staff: Observable<Staff[]>;
statusChange = new BehaviorSubject('');
get status(): string {
return this.statusChange.value;
}
set status(status: string) {
this.statusChange.next(status);
// console.log(status);
}
filterChange = new BehaviorSubject('');
get filter(): string {
return this.filterChange.value;
}
set filter(filter: string) {
this.filterChange.next(filter);
}
filteredData: Staff[] = [];
renderedData: Staff[] = [];
constructor(
public exampleDatabase: StaffService,public paginator: MatPaginator,public _sort: MatSort,) {
super();
// Reset to the first page when the user changes the filter.
this.filterChange.subscribe(() => (this.paginator.pageIndex = 0));
}
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<Staff[]> {
// Listen for any changes in the base data,sorting,filtering,or pagination
const displayDataChanges = [
this.exampleDatabase.dataChange,this._sort.sortChange,this.filterChange,this.paginator.page,];
// console.log(this.statusChange.value);
// this.exampleDatabase.getAll().subscribe(data =>(this.status = data.status));
this.exampleDatabase.getAll();
return merge(...displayDataChanges).pipe(
map(() => {
// Filter data
this.filteredData = this.exampleDatabase.data
.slice()
.filter((staff: Staff) => {
const searchStr = (
staff.firstName +
staff.lastName +
staff.email +
staff.fatherName +
staff.dob +
staff.contactNo
).toLowerCase();
return searchStr.indexOf(this.filter.toLowerCase()) !== -1;
});
// Sort filtered data
const sortedData = this.sortData(this.filteredData.slice());
// Grab the page's slice of the filtered sorted data.
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
this.renderedData = sortedData.splice(
startIndex,this.paginator.pageSize
);
return this.renderedData;
})
);
}
disconnect() {}
/** Returns a sorted copy of the database data. */
sortData(data: Staff[]): Staff[] {
if (!this._sort.active || this._sort.direction === '') {
return data;
}
return data.sort((a,b) => {
let propertyA: number | string = '';
let propertyB: number | string = '';
switch (this._sort.active) {
case 'id':
[propertyA,propertyB] = [a.id,b.id];
break;
case 'firstName':
[propertyA,propertyB] = [a.firstName,b.firstName];
break;
case 'email':
[propertyA,propertyB] = [a.email,b.email];
break;
case 'dob':
[propertyA,propertyB] = [a.dob,b.dob];
break;
case 'fatherName':
[propertyA,propertyB] = [a.fatherName,b.fatherName];
break;
case 'contactNo':
[propertyA,propertyB] = [a.contactNo,b.contactNo];
break;
}
const valueA = isNaN(+propertyA) ? propertyA : +propertyA;
const valueB = isNaN(+propertyB) ? propertyB : +propertyB;
return (
(valueA < valueB ? -1 : 1) * (this._sort.direction === 'asc' ? 1 : -1)
);
});
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。