Saltar al contenido

Filtro de fuente de datos de tabla de materiales con valor de columna

Después de de esta prolongada búsqueda de información pudimos resolver este rompecabezas que presentan algunos lectores. Te dejamos la solución y nuestro objetivo es resultarte de gran apoyo.

Solución:

De los docs.

Por ejemplo, el objeto de datos id: 123, nombre: ‘Sr. Smith ‘, favoriteColor:’ blue ‘ se reducirá a 123mr. smithblue. Si su filtro string era azul, entonces se consideraría una coincidencia porque está contenido en el string, y la fila se mostraría en la tabla.

Para anular el comportamiento de filtrado predeterminado, se puede configurar una función filterPredicate personalizada que toma un objeto de datos y un filtro string y vuelve true si el objeto de datos se considera una coincidencia.

Si desea utilizar el filtro solo columnas específicas, debe anular filterPredicate y la respuesta ya está aquí.

Este es el ejemplo práctico de filtrado.

table-filtering-example.html

No. element.position Name element.name Weight element.weight Symbol element.symbol

tabla-filtrado-ejemplo.ts

  import Component from '@angular/core';
    import MatTableDataSource from '@angular/material';

    /**
     * @title Table with filtering
     */
    @Component(
      selector: 'table-filtering-example',
      styleUrls: ['table-filtering-example.css'],
      templateUrl: 'table-filtering-example.html',
    )
    export class TableFilteringExample 
      displayedColumns = ['position', 'name', 'weight', 'symbol'];
      dataSource = new MatTableDataSource(ELEMENT_DATA);

      applyFilter(filterValue: string) 
        filterValue = filterValue.trim(); // Remove whitespace
        filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
        this.dataSource.filter = filterValue;
      
    

    export interface Element 
      name: string;
      position: number;
      weight: number;
      symbol: string;
    

    const ELEMENT_DATA: Element[] = [
      position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H',
      position: 2, name: 'Helium', weight: 4.0026, symbol: 'He',
      position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li',
      position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be',
      position: 5, name: 'Boron', weight: 10.811, symbol: 'B',
      position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C',
      position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N',
      position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O',
      position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F',
      position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne',
      position: 11, name: 'Sodium', weight: 22.9897, symbol: 'Na',
      position: 12, name: 'Magnesium', weight: 24.305, symbol: 'Mg',
      position: 13, name: 'Aluminum', weight: 26.9815, symbol: 'Al',
      position: 14, name: 'Silicon', weight: 28.0855, symbol: 'Si',
      position: 15, name: 'Phosphorus', weight: 30.9738, symbol: 'P',
      position: 16, name: 'Sulfur', weight: 32.065, symbol: 'S',
      position: 17, name: 'Chlorine', weight: 35.453, symbol: 'Cl',
      position: 18, name: 'Argon', weight: 39.948, symbol: 'Ar',
      position: 19, name: 'Potassium', weight: 39.0983, symbol: 'K',
      position: 20, name: 'Calcium', weight: 40.078, symbol: 'Ca', ];

puede usar filterPredicate para filtrar una columna específica como esta:

  ngOnInit() 
    this.dataSource.filterPredicate = (data: Element, filter: string) => 
      return data.name == filter;
     ;
   
 applyFilter(filterValue: string) 
    // filterValue = filterValue.trim(); // Remove whitespace
    // filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  

He cambiado el applyFilter() y agregado ngOnInit(). Ahora solo funciona nombre columna y exactamente el mismo valor (==)

Puede aprovechar mat-table-filter para fines de filtrado complicados.

Para filtrar por una columna, defina una entidad de ejemplo y complete solo la propiedad que pertenece a la columna correspondiente.

Aquí hay un ejemplo: https://stackblitz.com/github/HalitTalha/mat-table-filter-example

Puede filtrar por una columna dinámica, como en sin nombre de columna codificado, haciendo lo siguiente:

// On input focus: setup filterPredicate to only filter by input column
setupFilter(column: string) 
  this.dataSource.filterPredicate = (d: TableDataSourceType, filter: string) => 
    const textToSearch = d[column] && d[column].toLowerCase() ;


applyFilter(filterValue: string) 
  this.dataSource.filter = filterValue.trim().toLowerCase();

En la plantilla puede tener algo como esto:


  
    
  

O un ejemplo más complejo, cree dinámicamente una fila de encabezado con filtrado por columna:


     
       

Se consciente de que tu no poder tener varias filas de encabezado con el mismo keys, entonces esto no funcionará:



Sección de Reseñas y Valoraciones

Acuérdate de que puedes valorar esta noticia si te fue preciso.

¡Haz clic para puntuar esta entrada!
(Votos: 3 Promedio: 4)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *