Ways to conceal button for inactive edit row on a table

I am trying to implement inline editing for a table in my application. The requirement is to hide the "Edit" and "Delete" buttons for all other rows when the user clicks on the edit button of a particular row. I have attempted to achieve this using the current index, but it didn't work as expected. The same behavior should apply when the user clicks on the addNew button.

<a (click)="addNew()" class="mb-1 ml-1">Add New</a>
<table class="row-border table-bordered-no-confilct border-1 table">
  <thead>
    <tr>
      <th *ngFor="let head of headers">
        {{ head.name }} <span class="text-danger" *ngIf="head.required">*</span>
      </th>
    </tr>
  </thead>

  <tr *ngFor="let tableData of data; let i = index">
    <td>
     
       <div *ngIf="i">
            <i
            class="ace-icon fa fa-pencil-square-o bigger-150 text-success"
            data-toggle="tooltip"
            title="Edit"
            *ngIf="!tableData.isEditable"
            (click)="onEdit(tableData)"
          ></i>
          <i
            class="ace-icon fa fa-trash-o bigger text-danger ml-1"
            data-toggle="tooltip"
            title="Delete"
            *ngIf="!tableData.isEditable"
            (click)="onDelete(tableData)"
          ></i>
       </div>
      
        <i
        class="ace-icon fa fa-floppy-o bigger-150 text-success"
        data-toggle="tooltip"
        title="Save"
        *ngIf="tableData.isEditable"
        (click)="onSave(tableData)"
      ></i>
      <i
        class="ace-icon fa fa-times bigger-150 text-danger ml-1"
        data-toggle="tooltip"
        title="Cancel"
        *ngIf="tableData.isEditable"
        (click)="cancel(tableData, i)"
      ></i>

     
    </td>
    <td>{{ i + 1 }}</td>
    <ng-container *ngIf="tableData.isEditable; else viewable">
      <ng-container *ngFor="let head of headers">
        <ng-container *ngIf="head.mappedProperty">
          <td>
            <input
              *ngIf="
                head.dataType === 'text' ||
                head.dataType === 'number' ||
                head.dataType === 'checkbox'
              "
              [type]="head.dataType"
              [(ngModel)]="tableData[head.mappedProperty]"
              [checked]="tableData[head.mappedProperty]"
            />
          </td>
        </ng-container>
      </ng-container>
    </ng-container>

    <ng-template #viewable>
      <ng-container *ngFor="let head of headers">
        <ng-container *ngIf="head.mappedProperty">
          <td>{{ tableData[head.mappedProperty] }}</td>
        </ng-container>
      </ng-container>
    </ng-template>
  </tr>
</table>

ts

  onEdit(data): void {
    this.isNew = false;
    this.copyOfOriginalData = { ...data };
    this.data.map((item) => {
      item.isEditable = data.id === item.id;
    });
  }

Answer №1

If you want to achieve this functionality, you can simply use *ngIf with a property called "buttonStatus" in your data array or utilize the IsEditable property.
Below is a sample code snippet similar to yours:

<table class="style">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>email</th>
        <th></th>
    </tr>
    <tr *ngFor="let item of row; let i = index">
        <td><input type="text" ></td>
        <td><input type="text" ></td>
        <td><input type="text"></td>
        <td *ngIf="item.buttonStatus==true"> <button (click) = "deleteRow(i)"><i class="fa fa-trash"></i></button>
            <button (click)="editTable(i)">Edit</button>
            <button (click)="editDone()">Done</button>
        </td>
    </tr>
</table>

TS:

 row = [
{
  id: "",
  name: "",
  email: "",
  buttonStatus: true
},
{
  id: "",
  name: "",
  email: "",
  buttonStatus: true
},
{
  id: "",
  name: "",
  email: "",
  buttonStatus: true
}
];

editTable(x) {
//Activating buttons for only one row
for(let  i=0;i< this.row.length;i++){
  console.log(x);
  if(i==x)
  { 
    this.row[i].buttonStatus=true;
  }
  else
  {
      this.row[i].buttonStatus=false;
  }
}
// Include your code for editing data here
//{
//}
}

editDone(){
  //Activating buttons for all rows
  for (let i = 0; i < this.row.length; i++) {
   this.row[i].buttonStatus = true;
  }
}

Note: You can view and test the code on StackBlitz : Link
If you have any further queries, feel free to leave a comment.

Answer №2

Incorporate a custom attribute in every tableData element such as displayButtons and adjust the value accordingly within your tableData, utilizing the [hidden]="!displayButtons attribute.

The [hidden] attribute is applicable to all HTML Elements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the value of a JSON string

I'm having trouble accessing a json value in this example. No alert is being produced. Can you help me figure out what the problem is? This is the JSON data I am working with: { "response": [ { "id": "0", "elementName": "osname", "isEqual": t ...

Operating two independent Angular applications simultaneously on a single webpage

I'm currently developing an application that allows multiple Angular applications to be embedded within a main frame. Currently, I am using IFrames for this purpose, which is functioning well but has its limitations. I am exploring ways to embed ano ...

Choose all div elements with a specified class from a variable

How can I retrieve all div elements with the "test" class from a variable and insert them into another div? var response = xmlhttp.responseText; var selectedDivs = $(response).find('.test'); $('.anotherdiv').prepend(selectedDivs); ...

Changing the class name in HTML depending on the size of the screen

I'm attempting to dynamically change the class tag's name when a user visits the page based on the screen size. Below is the code snippet I've used: <!DOCTYPE html> <html> <body onload="changeClass()"> <section class=" ...

Angular 4: Decoding the json_callback response from the server

When using Angular 4, I made a GET request to the following URL: Here is the code I used: this.http.get('https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=JSON_CALLBACK', { params: { format: 'json', tagmode: & ...

Error: TypeError encountered during UI Runtime JSON conversion of Circular Data Structure

I'm facing an issue while attempting to parse and stringify certain JSON data. The error occurs on this specific line of code: this.copyOfColumns = JSON.parse(JSON.stringify(Object.assign([], this.columns))); Below is the complete @Input (using Ang ...

Tips on managing the onKeyUp event in a ReactJS form

Here is a simple JavaScript function called numericOdds implemented in home.js file: function numericOdds(e) { var valid = /^[1-9]{1}[0-9]{0,1}$/ var number = /^[1-9]{1}$ | ^[1-9]{1}[0-9]{1}$/ var lastValid = ''; var n; console.log(&apo ...

Shifting elements in an array using Javascript

I am working with two arrays, one containing numbers and the other containing objects of the same length: var a = [2, 0, 1], b = [obj1, obj2, obj3]; My goal is to rearrange the items in array 'b' based on the positions of the numbers in array & ...

VueJS 3 - Issue with applying the <router-link-active> class to routes that share the same path starting name

In my navigation bar, I have created 3 links which are all declared at the root level of the router object. I've applied some simple styling to highlight the active link on the navbar using the <router-link-active> class. Everything works as exp ...

Guide on loading numerous JavaScript files into a database using the mongo shell

I am faced with the task of loading multiple js files that contain collections creations and seeds into my database using the mongo command. Currently, I have been manually loading data from each file one by one like so: mongo <host>:<port>/< ...

Create-react-app fails to generate a template even though the react framework is fully updated

I attempted to set up a fresh react directory using npx create-react-app. Unfortunately, every solution I tried resulted in the template not being provided, with the common suggestion being that my version of create-react-app may be outdated. I verified t ...

What causes the variance in timestamps between JavaScript and PHP?

I am facing a discrepancy between the JavaScript and PHP timestamps I have created. There is roughly a 170-second difference between the two. 1302162686 PHP - time() 1302162517 JavaScript - Math.round(new Date().getTime() / 1000) If anyone has any insi ...

finishing an observation after a sequence of responses

In my current scenario, I am dealing with an observable that sequentially calls promises within it. My goal is to have the observable complete only after all promises in a forEach loop have been successfully processed. However, I am facing an issue where ...

The jQuery window.load() function fails to execute on iOS5 devices

I added a basic loading div to my website that fades out once the entire page has finished loading. The code I used is simple: $(window).load(function(){ $('#loading').fadeOut(500); }); While this works well on all desktop browsers and Chro ...

Combining arrays of objects using JSON format in JavaScript

Here is an example of a JSON file: [ { "stores": [ { "name" : "My store", "location" : "NY" }, { "name" : "Other store", ...

Troubleshooting Pagination Challenges in Node.js Using Mongoose and Enhancing Query Performance

Having trouble with my database query using Mongoose. I am setting values but not getting the correct result, and I also want to optimize the query. Currently, I am using mongoose to count how many records match certain query parameters for pagination, whi ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Utilize Google Maps API to showcase draggable marker Latitude and Longitude in distinct TextFields

I am currently utilizing the Google Maps example for Draggable markers. My objective is to showcase the latitude and longitude values within separate TextFields, where the values dynamically change as I drag the marker. Once the user stops dragging the mar ...

Angular translation for datetimepicker

Looking to implement a datepicker that allows selecting the hours, so I decided to add an Angular component. After searching, I found the perfect component: https://www.npmjs.com/package/angular-bootstrap-datetimepicker Although this component is original ...

Is there a way to obtain the tasklist result of exec() from child_process and convert it to JSON format?

When I use the tasklist command with child_process, the stdout returns processes in Unicode string format that is not easily queryable. Here is the code snippet: var exec = require('child_process').exec; ... exec('tasklist', function( ...