【发布时间】:2019-10-29 00:14:07
【问题描述】:
我正在使用 Angular 版本 7 开发一个 Angular 项目。我有一个显示一些 json 对象的表。在每个 json 对象中,我添加了 2 个按钮,当每个按钮被选中时,我都会有条件地显示它们。
我的意思是,当我单击“编辑”按钮时,我希望显示“不编辑”按钮,反之亦然,仅在我按下按钮的那一行。但是发生的情况是,当我单击特定行的“编辑”按钮时,其他行的所有其他按钮都会更改。
我该怎么做?
myapp.component.html 文件:
<table>
<thead>
<tr>
<th scope="col" translate>Name</th>
<th scope="col" translate>Description</th>
</tr>
</thead>
<tbody>
<tr *ngFor=" let product of products">
<td>{{product.name}}</td>
<td>{{datasource.description}}</td>
<td>
<button *ngIf="allowEdit" (click)="edit(product)">
Edit
</button>
<button *ngIf="allowNoEdit" (click)="noEdit(product)">
No Edit
</button>
</td>
</tr>
</tbody>
</table>
myapp.component.ts 文件:
allowEdit: boolean = true;
allowNoEdit: boolean = false;
edit(product) {
this.allowEdit= !this.allowEdit;
this.allowNoEdit= !this.allowNoEdit;
}
noEdit(product) {
this.allowEdit= !this.allowEdit;
this.allowNoEdit= !this.allowNoEdit;
}
【问题讨论】:
-
您必须为每一行添加 *ngIf,例如。 *ngIf="product.allowEdit",然后您可以在单击方法中切换它,allowEdit 和 noEdit 以适用于选定的产品 product.edit = !product.edit,它应该适用于每一行。
-
@mocni_T 你能给出示例代码吗?谢谢
-
检查我的代码
-
我会使用 CSS。单击编辑按钮时,我会在该行中添加一个类。此类导致编辑按钮消失并出现 noedit 按钮。单击 noedit 按钮时,您然后从行中删除 css 类
-
@schlonzo 我不会。建议尽可能使用
*ngIf,以避免angular执行不必要的检查。
标签: javascript angular typescript angular7