首页 > 解决方案 > 角细节组件。仅显示基于 url 的数组的某些元素

问题描述

我正在关注英雄教程的角度之旅(https://angular.io/tutorial/toh-pt6)。我想看看是否有可能让详细信息页面循环通过一个数组访问基于路由到的页面的特定元素

就像教程一样,我制作了一个详细信息页面,通过单击表格中的按钮导航到该页面。

我的 routing.module.ts

const routes: Routes = [{
  path: '',
  component: DefaultComponent,
  children: [{path: '', component: DashboardComponent},
    {path: 'detail/:id', component: DeviceDetailComponent}
  ]
},

我的dashboard.componenent.html 中的按钮

<!-- Button Column -->
  <ng-container matColumnDef="actions">
    <th mat-header-cell  *matHeaderCellDef > Actions </th>
    <td mat-cell *matCellDef="let device" >
      <button mat-button routerLink= "/detail/{{device.id}}">View</button>
    </td>
  </ng-container>

我有一个 1d 1-5 的数组,当我单击按钮时,它会正确路由到该 url 并显示一条有效的简单消息。我的 detail.componenet.html

<p>device{{device.id}} works</p>

我的计划是根据单击的 id 显示数组中的某些元素。

例如我有一个这样的数组:

export interface Devices {
  name: string;
  id: number;
  serialNo: number;
}

export const DEVICES: Devices[] = [
  {id: 1, name: 'Device 1', serialNo: 135421},
  {id: 2, name: 'Device 2', serialNo: 125240},
  {id: 3, name: 'Device 3', serialNo: 124350},
  {id: 4, name: 'Device 4', serialNo: null},
  {id: 5, name: 'Device 5', serialNo: null},
];

是否可以仅显示某些元素,例如如果您单击设备 1-3,它将路由到详细信息/(1-3)显示名称和序列号。但是,如果您单击 4/5,它只会显示名称。

我循环遍历对象数组的唯一经验是这样的

 <tr *ngFor="let d of DEVICES">
          <td>{{ d.id }}</td>
          <td>{{ d.name }}</td>
          <td>{{ d.serialNo }}</td>

是否有可能使 d.serialNo 仅出现在 1-3

另外我觉得我应该指出,通过制作组件 device1-5 并进行不同的设置,我已经能够正确地做到这一点。但我很好奇我是否可以只用一个组件来实现这一点。就像教程中的细节组件一样

标签: javascriptarraysangular

解决方案


应用*ngIf并检查 serialNo 是否以 1、2 或 3 开头

<tr *ngFor="let d of DEVICES">
      <td *ngIf="showEntry(d)">{{ d.id }}</td>
      <td *ngIf="showEntry(d)">{{ d.name }}</td>
      <td *ngIf="showEntry(d)">{{ d.serialNo }}</td>

TS

showEntry(device: Devices): boolean {
     return !!(device && 
         (device.serialNo.toString().startsWith('1') ||
          device.serialNo.toString().startsWith('2') ||
          device.serialNo.toString().startsWith('3')
     );
}

推荐阅读