Angular 如何获取当前点击的客户端数据并向其嵌套子数组添加新对象
如何获取当前点击的客户端
你在渲染客户端列表的模板中,通过点击事件直接传递当前遍历的客户端对象即可,示例模板代码如下:
<!-- 客户端列表所在组件的模板 --> <div *ngFor="let client of clients"> <p>{{client.name}}</p> <button (click)="onSelectClient(client)">新增Installation</button> </div>
在对应组件中声明变量存储选中的客户端,再通过父子组件传值、或者路由传参把选中的客户端传给AddInstallationComponent即可。如果是路由跳转的场景,也可以传递当前客户端的id,在新增页通过id从clientService拉取完整的客户端数据。
现有代码的问题修正
- 接口属性名拼写错误:原JSON结构中子数组名为
installations(复数),你代码里写的是installation(单数) - 直接从
installation数组上取name、key属性是错误的,数组本身没有这两个属性,你应该单独声明一个对象存储表单填写的新installation数据
修正后的代码示例
export class AddInstallationComponent implements OnInit { // 存储当前选中的客户端,从列表页传递过来 selectedClient?: any; // 单独存储新填写的installation数据,和表单绑定 newInstallation = { name: '', key: '' }; constructor(private clientService: ClientService, private route: ActivatedRoute) { } ngOnInit(): void { // 如果是路由传id的场景,在这里查客户端数据 // const clientId = this.route.snapshot.params['clientId']; // this.clientService.getClientById(clientId).subscribe(res => this.selectedClient = res); } saveInstallation(): void { if (!this.selectedClient) return; // 初始化installations数组(避免未定义的情况) if (!this.selectedClient.installations) { this.selectedClient.installations = []; } // 把新数据加入数组 this.selectedClient.installations.push({ // 生成唯一id,也可以等后端返回后再赋值 id: Date.now().toString(), name: this.newInstallation.name, key: this.newInstallation.key }); // 这里可以调用service的接口把更新后的客户端数据同步到后端 // this.clientService.updateClient(this.selectedClient).subscribe(...) // 提交后清空表单 this.newInstallation = {name: '', key: ''}; } // 如果是父子组件场景,列表页传过来的客户端可以用@Input接收 // @Input() set client(val: any) { // this.selectedClient = val; // } }
内容的提问来源于stack exchange,提问作者silviaa11
相关产品推荐
相关产品推荐

