Tutorial: Listas dinámicas con Material Angular



Requisitos:
  • Tener instalado NodeJs
  • Tener instalado Angular

Instrucciones:

Crear una aplicación de angular:
ng new my-app
Agregar la libreria Material (https://material.angular.io/)
ng add @angular/material
En app.module.ts agregar:
import { MatListModule} from '@angular/material/list';
@NgModule ({....
  imports: [...,
  MatListModule,
…]
})
En app.component.ts, crear las listas:
list1 = [ //left
    {id: 1, name: "Obj 1"},
    {id: 2, name: "Obj 2"},
    {id: 3, name: "Obj 3"},
    {id: 4, name: "Obj 4"},
    {id: 5, name: "Obj 5"},
  ]

    list2 = [ //right
    {id: 6, name: "Obj 6"},
    {id: 7, name: "Obj 7"},
    {id: 8, name: "Obj 8"},
    {id: 9, name: "Obj 9"},
    {id: 10, name: "Obj 10"},
  ]
Y luego las funciones para pasar de una lista a la otra:
moveLeft(rightList){
    let elem = rightList.selectedOptions.selected.map((e)=>e.value)

      this.list1 = this.list1.concat(elem);

      this.list2 = this.list2.filter(
        function(e) {
          return this.indexOf(e) < 0;
        },
        this.list1)

  }

  moveRight(leftList){
   let elem = leftList.selectedOptions.selected.map((e)=>e.value)

      this.list2 = this.list2.concat(elem);

      this.list1 = this.list1.filter(
        function(e) {
          return this.indexOf(e) < 0;
        },
        this.list2)
  }

En app.component.html vamos a usar una mat-list-selection:

<div class="container">
  <div class="col">
     <h2>Left</h2>
                    <mat-selection-list #left  class="wards-list">
                      <mat-list-option  *ngFor="let elem of list1" [value]="elem" role="listitem">{{elem.name}}</mat-list-option >                     
                    </mat-selection-list>
  </div>
  <div class="col-small">
      <button mat-raised-button (click)="moveRight(left)" class="mb-3" color="primary"> >> </button>
      <button mat-raised-button  (click)="moveLeft(right)" class="mb-3" color="warn"> << </button>
  </div>
  <div class="col">
    <h2>Right</h2>
        <mat-selection-list #right class="wards-list">
          <mat-list-option *ngFor="let elem of list2" [value]="elem" role="listitem">{{elem.name}}</mat-list-option >                     
        </mat-selection-list>
  </div>
</div>

Ver ejemplo:
 


Comentarios