обновление строки в таблице в угловых 2 - PullRequest
0 голосов
/ 02 мая 2018

Привет, я работаю над угловым 2, вставляя обновление и удаляя строку в угловом 2. В ngFor я привязываю данные к таблице. Я создал кнопку обновления в цикле ngFor.

При нажатии кнопки «Обновить» для отдельных строк мне нужна только эта строка с текстовыми полями вместо всех строк. К сожалению, я получаю за все записи. Я знал это из-за свойства, связанного со всеми рядами. Но как я могу преодолеть, чтобы убедиться, что только отдельные щелкнуть строки, чтобы получить в режиме редактирования, как текстовые поля. Мой код был как показано ниже:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public enableEdit = true;

  showcreate: boolean=false;
  public items=[];
  public FirstName="";
  public LastName="";
  public MobileNumber="";
  public PinCode="";
  public City=""; 
  public CollageName="";        
  public Percent=""; 
  public conformdelete;
  public edit = false;
  public btncreate =false;
  public indexVal:any;
      constructor(){
        if(localStorage.getItem("items"))
        this.items = JSON.parse(localStorage.getItem("items"))
       }

  delete(index){    
    if(confirm("Are you sure you want to delete this item?") == true){
      this.items.splice(index,1);
      localStorage.setItem("items",JSON.stringify(this.items))
     }
  }
  update(event, index){
    debugger;
    console.log(event);
    console.log(index);
    this.enableEdit = false;
  }
  save(index){
    // console.log("save",i)
    // this.indexVal = i;
    this.enableEdit = true;

  }
  cancel(){

        this.enableEdit = true;
  }

  btnsubmit(){
    this.items.push({
      "FirstName":this.FirstName,
      "LastName":this.LastName,
      "MobileNumber":this.MobileNumber,
      "PinCode":this.PinCode,
      "City":this.City, 
      "CollageName":this.CollageName,                 
       "Percent":this.Percent         

     })
     localStorage.setItem("items",JSON.stringify(this.items))

       }

      }

app.component.html:

<table border="2">
  <thead>
    <tr>
    <th>FirstName</th>
    <th>LastName</th>
    <th>MobileNumber</th>
    <th>PinCode</th>
    <th>City</th>
    <th>CollageName</th>            
    <th>Percent</th>
    <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let i of items; let index = index">
      <td><input *ngIf="!enableEdit" [(ngModel)]="i.FirstName"> <span *ngIf="enableEdit">{{i.FirstName}}</span></td>
      <td><input *ngIf="!enableEdit" [(ngModel)]="i.LastName"> <span *ngIf="enableEdit">{{i.LastName}}</span></td>
      <td><input *ngIf="!enableEdit" [(ngModel)]="i.MobileNumber"> <span *ngIf="enableEdit">{{i.MobileNumber}}</span></td>
      <td><input *ngIf="!enableEdit" [(ngModel)]="i.PinCode"> <span *ngIf="enableEdit">{{i.PinCode}}</span></td>
      <td><input *ngIf="!enableEdit" [(ngModel)]="i.City"> <span *ngIf="enableEdit">{{i.City}}</span></td>        

      <td><input *ngIf="!enableEdit" [(ngModel)]="i.CollageName"> <span *ngIf="enableEdit">{{i.CollageName}}</span></td>                 
      <td><input *ngIf="!enableEdit" [(ngModel)]="i.Percent"> <span *ngIf="enableEdit">{{i.Percent}}</span></td> 
      <td>
        <button *ngIf="enableEdit" (click)="delete(index)">Delete</button>
        <button *ngIf="enableEdit" (click)="update($event,index)" class="update">Update</button>
        <button *ngIf="!enableEdit" (click)="save(index)">save</button>
        <button *ngIf="!enableEdit" (click)="cancel(index)" >cancle</button>
    </td>
    </tr>
  </tbody>
</table>

1 Ответ

0 голосов
/ 03 мая 2018

Проблема заключается в том, что при нажатии одной из ваших кнопок строк условие «enableEdit» универсально для всех строк, оно отражается во всех строках. Одним из возможных решений является добавление дополнительной пары ключ-значение в массив таблицы, чтобы вы могли использовать каждую строку, используя ее индекс.

Пример:

в вашем component.ts,

constructor(){
        if(localStorage.getItem("items"))
        this.items = JSON.parse(localStorage.getItem("items"));

        /* add an extra key value pair named "edit", and initially set it to false. So all the rows will be showing "Delete" and "Update" buttons initially */
        this.items.forEach(function (eachItem){ 
          eachItem.edit = false;
        });
       }


       /* function for update or cancel functionalities */
       updateCancel(event, index,action:string){
         this.items[index].edit = true; /* selects the items with index number and swaps the buttons*/

         if(action == "cancel"){
           this.items[index].edit = false;
         }
       }

       /* function for save or delete functionalities */
       saveDelete(index, action:string){
         this.items[index].edit = false;

         if(action == "delete"){
           if(confirm("Are you sure you want to delete this item?") == true)
          {
            this.items.splice(index,1);
            this.items[index].edit = true;
            localStorage.setItem("items",JSON.stringify(this.items))
         }
       }

    }

В вашем app.component.html файле измените область кнопки td на новые имена функций и, если условие

   <td>
        <button *ngIf="!i.edit" (click)="saveDelete(index,'delete')">Delete</button>
        <button *ngIf="!i.edit" (click)="updateCancel($event,index,'update')" class="update">Update</button>
        <button *ngIf="i.edit" (click)="saveDelete(index,'save')">Save</button>
        <button *ngIf="i.edit" (click)="updateCancel($event,index,'cancel')">cancel</button>
      </td>

Это решение сработало для меня. Спасибо.

...