NativeScript - Filter a ListView data by tabs from

2019-09-20 13:23发布

问题:

How can I show up by demand only data related by specific room?

Below my Json data:

{
  "rooms": [
    {
      "id": 1,
      "name": "Room 01",
      "content": "Content 01"
    },
    {
      "id": 2,
      "name": "Room 02",
      "content": "Room 02"
    }
  ],
  "tables": [
    {
      "id": 1,
      "number": 1,
      "roomId": 1
    },
    {
      "id": 2,
      "number": 2,
      "roomId": 1
    },
    {
      "id": 3,
      "number": 3,
      "roomId": 2
    }
  ]
}

My template:

<TabView [(ngModel)]="tabSelectedIndex" selectedColor="#FF0000">
  <ng-container *ngFor="let tab of roomsList">
    <StackLayout *tabItem="{title: tab.name}">
      <ListView [items]="tablesList">
        <ng-template let-item="item">
          <Label [text]="item.number"></Label>
        </ng-template>
      </ListView>
    </StackLayout>
  </ng-container>
</TabView>

My class Component using Angular core and my personal FileReader class to read and return a JSON data. See it below:

export class DataItem {
  constructor(public name: string, public content: string) {}
}

export class TableItem {
  constructor(public number: number) {}
}

@Component({
  selector: 'my-app',
  templateUrl: 'app.component.html'
})

export class AppComponent implements OnInit {
  // Your TypeScript logic goes here
  public roomsList: Array<DataItem>;
  public tabSelectedIndex: number;
  public tablesList: Array<TableItem>;

  private loadRooms(roomsList: Array<DataItem>) {
    this.tabSelectedIndex = (!!roomsList.length) ? 1 : 0;
    this.roomsList = roomsList.map(item => new DataItem(item.name, item.content));
  }

  private loadTables(tablesList: Array<TableItem>) {
    this.tablesList = tablesList.map(item => new TableItem(item.number));
  }

  private loadInterface() {
    FileReader
      .readJSON('./config/interface.json')
      .then((output: Array<object>) => {
        const roomsList = output['rooms'];
        const tablesList = output['tables'];

        this.loadRooms(roomsList);
        this.loadTables(tablesList);
      });
  }

  constructor() {}

  ngOnInit() {
    this.loadInterface();
  }
}

References:

  • NativeScript - TabView-ng
  • Dynamic tabs in TabView-ng NativeScript
  • Filter ListView using angular2 in NativeScript

回答1:

I recent solved that creating a new array [] and increment using map() + filter() + push() the filtered into the new array.

private filteredRooms(roomsList, tablesList) {
    const filteredRooms = [];

    roomsList.map(room => {
      const filteredTables = tablesList.filter((t: TableItem) => t.roomId === room.id);
      const filteredRoom = room;

      filteredRoom['tables'] = filteredTables;

      filteredRooms.push(filteredRoom);
    });

    return filteredRooms;
    }

And change the tablesList to tables on ListView.