angular - 如何通过以角度路由到相同的组件来传递不同的数据(对象数组)
问题描述
我的dashboard.ts
. 如何将此数据传递到“ClientsListComponent”。
仪表板.html
<a routerLink="dashboard/my-clients" >My Clients</a>
<a routerLink="dashboard/all-clients">All Clients</a>
app.module.ts
RouterModule.forRoot(
[ { path: '', component: LoginComponent},
{ path: 'dashboard', canActivate: [AuthguardGuard], component: DashboardComponent},
{ path: 'dashboard/add-new-client', component: ClientFormComponent, canActivate: [AuthguardGuard]},
{ path: 'dashboard/all-clients', component: ClientsListComponent, canActivate: [AuthguardGuard]},
{ path: 'dashboard/my-clients', component: ClientsListComponent, canActivate: [AuthguardGuard]}
]
客户端列表组件.ts
@Component({
selector: 'clients-list',
templateUrl: './clients-list.component.html',
styleUrls: ['./clients-list.component.css']
})
export class ClientsListComponent implements OnInit {
@Input() clients: Client[] = []; // I print this data on screen.
@Input() title: '';
constructor() { }
ngOnInit() {
}
}
解决方案
有几种方法可以做到这一点。dashboard.ts
可以使用export
关键字导出保存数组的变量。然后另一个组件可以使用import
语句访问该数组。
另一种方法是使用在创建组件时传递的构造函数参数,使用@Input()
组件定义中的装饰器,就像您当前拥有的一样。
在父组件的模板中,您可以使用以下语法传递构造函数参数:
<myapp-clientslist
[arg1]="arg1" [arg2]="arg2">
</myapp-clientslist>
双引号中的字符串被评估为 JavaScript。当然,这要求父组件可以使用变量,或者通过 URL 参数、导入语句等以相同的方式被另一个父组件接收。
推荐阅读
- swift - 在 Swift 中显示父控制器的导航栏时,在另一个控制器上方显示具有透明视图的模态视图控制器
- bash - Bash 将变量传递给字符串
- java - 我的代码在 for 循环“java.util.InputMismatchException”中输入字符串时显示错误?
- excel - 动态汇总相邻单元格包含某些文本的单元格
- javascript - 基于表单字段数据的上传目录厉害吗?
- .net - .NET 框架 4.8 的传输层安全性 (TLS 1.3)
- scala - 为什么 cp 命令在不注意添加 -e 选项的情况下会出错?
- shopify - 太多/无限循环问题 - Shopify
- json - 如何使用 Swift 5 从 URL 解析 JSON 数据并附加到 UiLabel
- java - 带有 Libvirt c 代码的 JNA。我做错了什么?