NativeScript - 通过TabView-ng中的选项卡过滤ListView数据

时间:2018-05-09 18:08:07

标签: angular nativescript angular2-nativescript

如何按要求仅显示特定房间相关的数据?

在我的Json数据下面:

{
  "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
    }
  ]
}

我的模板:

<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>

我的类Component使用Angular核心和我的个人FileReader类来读取和返回JSON数据。见下文:

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();
  }
}

参考文献:

1 个答案:

答案 0 :(得分:0)

我最近解决了创建新数组[]并使用map() + filter() + push()进行增量过滤到新数组中。

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;
    }

并将ListView上的tablesList更改为tables