Angular 7中如何根据指定行的列值默认选中复选框和选择框
实现编辑弹窗默认选中对应状态复选框及完善关闭功能
没问题,我帮你调整代码来实现这两个需求:根据点击行的status值默认选中弹窗里的对应复选框,同时确保关闭链接正常工作。
第一步:完善组件类逻辑
首先我们需要在组件里存储当前编辑行的状态ID,这样才能和弹窗里的复选框做匹配。修改app.component.ts:
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { dotsh: any; hoverIndex: number = -1; groups: any; test: any; statusdata: any; block: any; closeit: any; // 新增:存储当前编辑行的状态ID数组 currentRowStatusIds: number[] = []; onHover(i: number) { this.hoverIndex = i; } columns = ["name", "Items", "status", "Action"]; edit(dataItem) { // 注意数据里的状态字段是大写的Status,不是小写status console.log(dataItem.Status); // 提取当前行所有状态的ID,存入数组 this.currentRowStatusIds = dataItem.Status.map(status => status.id); this.block = true; } ngOnInit() { this.closeit = true; this.block = false; this.test = false; this.groups = [ {"id":1,"name":"pencils","items":"red pencil","Status":[{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}],"loc":[{"id":1,"name":"loc 1"},{"id":2,"name":"loc 2"},{"id":3,"name":"loc 3"}]}, {"id":2,"name":"rubbers","items":"big rubber","Status":[{"id":1,"name":"green"},{"id":2,"name":"red"}],"loc":[{"id":1,"name":"loc 2"},{"id":2,"name":"loc 3"}]}, {"id":3,"name":"rubbers1","items":"big rubber1","Status":[{"id":1,"name":"green"}],"loc":[{"id":1,"name":"loc 2"},{"id":2,"name":"loc 3"}]} ]; this.statusdata = [{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}]; } close() { this.block = false; // 关闭弹窗时清空状态ID数组,避免影响下次打开 this.currentRowStatusIds = []; } }
第二步:修改弹窗复选框的绑定逻辑
接下来调整app.component.html里的弹窗部分,让复选框根据存储的状态ID自动选中:
<table class="table border"> <thead> <tr> <ng-container *ngFor="let column of columns; let i = index"> <th>{{ column }}</th> </ng-container> </tr> </thead> <tbody> <tr *ngFor="let row of groups;let i = index"> <td>{{row.name}}</td> <td>{{row.items}}</td> <td > <span class="status" *ngFor="let item of row.Status ;let j = index"> {{item.name}} </span> <span *ngIf = "i == hoverIndex" class="hover-details"></span> </td> <td style="cursor:pointer;" (click)="edit(row);">Edit</td> </tr> </tbody> </table> <div style="border: 1px solid #000; padding: 10px; display: flex; width: 100%; margin-top: 1%;" *ngIf="block"> Status-checkbox: <div style="float:left" *ngFor="let status of statusdata"> <!-- 绑定checked属性:判断当前状态ID是否在currentRowStatusIds数组里 --> <input type="checkbox" [checked]="currentRowStatusIds.includes(status.id)" [value]="status.id" />{{status.name}} </div> <div (click)="close();" style="cursor:pointer;float:right;margin-left:10%;">close</div> </div>
逻辑说明
- 点击编辑按钮时,我们会把当前行的所有状态ID提取出来存入
currentRowStatusIds数组; - 弹窗里的每个复选框通过
includes方法判断自己的ID是否在这个数组里,从而决定是否默认选中; - 关闭弹窗时不仅隐藏弹窗,还清空
currentRowStatusIds,确保下次打开新行的弹窗时不会残留之前的选中状态。
内容的提问来源于stack exchange,提问作者UIAPPDEVELOPER
相关产品推荐
相关产品推荐

