首页 文章

按钮上的另一个按钮单击Angular 2更改dinamically创建的模板元素

提问于
浏览
-3

得到了下一个模板:

<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();
}
...

1 回答

  • 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>
    

相关问题