获得下一个模板:
<table class="table table-sm" style="background-color: lightgrey;">
<tbody>
<tr *ngFor="let category of categories">
<td class="central">
<p>{{category.categoryName}}</p>
<!--<input class="form-control" value="{{category.categoryName}}">-->
</td>
<td><button type="button" class="btn btn-outline-warning">Edit</button></td>
<td><button type="button" class="btn btn-outline-danger">Delete</button></td>
<!--<td><button type="button" class="btn btn-outline-warning">Done</button></td>-->
<!--<td><button type="button" class="btn btn-outline-danger">Cancel</button></td>-->
</tr>
</tbody>
</table>
使用* ngFor指令我在第一列中创建表,其中有一个类别的名称(每个都有categoryId字段),第二列有编辑按钮,第三列 - 删除按钮。
我希望拥有下一个功能:当用户点击编辑按钮时,其行中带有类别名称的p元素需要被具有类别名称值的Input元素替换,同时需要编辑和删除按钮替换为完成和取消按钮。仅在单击“编辑”按钮的行中进行更改。
获得了下一个类别模型:
export class Category {
constructor(
public categoryId: number,
public categoryName: string
){}
}
这是组件文件的一部分:
import {Component, OnInit} from '@angular/core';
import {Category} from "./models/category";
import {CategoryService} from "./category.service";
@Component({
selector: 'my-categories',
templateUrl: './categories.component.html',
})
export class CategoriesComponent implements OnInit{
categories: Category[];
constructor (private categoryService: CategoryService) {}
ngOnInit() {
this.getCategories();
}
...
答案 0 :(得分:0)
所以,这是决定: 起初我已经为Category类添加了布尔属性“visibility”:
export class Category {
constructor(
public categoryId: number,
public categoryName: string,
public visibility: boolean = true
){}
}
然后我将[hidden]属性添加到模板的所有DOM元素中,我需要根据编辑 - 取消按钮单击隐藏/显示。此属性的值最初设置为初始显示元素的某些类别的可见性属性(true)值,以及最初隐藏元素的可见性(为false)。由于编辑 - 取消按钮的单击事件,我已将可见性更改为反向值:
<table class="table table-sm" style="background-color: lightgrey;">
<tbody>
<tr *ngFor="let category of categories">
<td class="central">
<p [hidden]="category.visibility">{{category.categoryName}}</p>
<input [hidden]="!category.visibility" class="form-control" value="{{category.categoryName}}">
</td>
<td><button [hidden]="category.visibility" type="button" class="btn btn-outline-warning" (click)="category.visibility = !category.visibility">Edit</button></td>
<td><button [hidden]="category.visibility" type="button" class="btn btn-outline-danger">Delete</button></td>
<td><button [hidden]="!category.visibility" type="button" class="btn btn-outline-warning">Done</button></td>
<td><button [hidden]="!category.visibility" type="button" class="btn btn-outline-danger" (click)="category.visibility = !category.visibility">Cancel</button></td>
</tr>
</tbody>
</table>