javascript - 角细节组件。仅显示基于 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 并进行不同的设置,我已经能够正确地做到这一点。但我很好奇我是否可以只用一个组件来实现这一点。就像教程中的细节组件一样
解决方案
应用*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')
);
}
推荐阅读
- python - Python-在contourf图中压缩y轴的下端
- google-cloud-platform - 用于内部认证请求的 Google Cloud Function 403
- excel - VBA在word文档的页脚中查找和替换
- google-sheets - 尝试将 Coinbase Pro API 导入 Google 表格时出现解析错误
- azure-devops - 多配置 Azure Devops 2019 构建管道中的条件管道(Visual Studio 测试)任务
- javascript - 未捕获的类型错误:无法读取 node.js 上未定义的属性“长度”
- c++ - 为什么这不能在 Linux 上运行,但在 OSX 上运行良好?
- javascript - Nodejs - 得到猫鼬打字稿错误
- java - GSON 在运行 toJSON 时导致 StackOverFlow 错误
- python - 遍历列表并按顺序将每个元素附加到一组新列表