What is the method to activate a chosen cell within an angular table?

When a cell is clicked, it should be the only open and focused cell. If another cell is clicked, the previous one should close. Currently, multiple sunsetDate cells can be open at the same time, which is incorrect.

How can this be handled in angular?

#screenshot

https://i.sstatic.net/PXObA.png

#html code

<td (click)="editStatus(data, 'sunsetDate' , i)"
                [ngClass]="indexEditing==i && selectedCell === 'sunsetDate' ? 'editing-cell' : ''"
                [ngClass]="!data.isRequired ? 'blank-cell' : ''" class="date-text-right">
                <mat-form-field appearance="fill" *ngIf="indexEditing==i && selectedCell === 'sunsetDate'; else viewSunsetDate">
                    <mat-label>Choose a date</mat-label>
                    <input (blur)="blur()" [(ngModel)]="data.sunsetDate" (keyup.enter)="dateChange(data,'parent','sunsetDate')"
                        (keydown.tab)="dateChange(data,'parent','sunsetDate')" matInput (dateChange)="dateChange(data,'parent','sunsetDate')"
                        [matDatepicker]="picker" #inputField>
                    <mat-hint>MM/DD/YYYY</mat-hint>
                    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                    <mat-datepicker #picker></mat-datepicker>
                </mat-form-field>
                <ng-template #viewSunsetDate>
                    <p> {{data.sunsetDate | date:'MM/dd/YYYY'}} </p>
                </ng-template>
            </td>
            <td (click)="editStatus(data, 'status' , i)"
                [ngClass]="{'editing-cell':indexEditing==i && selectedCell === 'status', 'blank-cell': !data.isRequired && !data.isHeaderCategory , 'uneditable-cell' : !data.isRequired && data.isHeaderCategory}"
                style="text-align: center;">
                <mat-form-field style="width: 100px; height: 30px;" appearance="fill"
                    *ngIf="indexEditing==i && selectedCell === 'status'; else viewStatus" autofocus>
                    <mat-select (blur)="blur()" (openedChange)="openedChange($event, data, 'parent' , 'status')" [(value)]="data.status">
                        <mat-option *ngFor="let status of statuses" [value]="status.viewValue"> {{status.viewValue}}
                        </mat-option>
                    </mat-select>
                </mat-form-field>
                <ng-template #viewStatus>
                    <p> {{data.status}} </p>
                </ng-template>
            </td>

#ts code

@ViewChild('editDatePickerInputCell') editDatePickerInputCell:any;

     editDateTest(value: EntitlementTransactionTemplateDto, columnName: string) {
        value.editing = false
        value.editing = !value.editing
        this.selectedCell = columnName
    
        console.log('columnName' , columnName)
        console.log('Value' , value)
    
    
        if (value.editing) {
          setTimeout(() => {
            this.focusOnEditCell();
          }, 0)
        }
      }

      focusOnEditCell() {
    setTimeout(()=>{
      if(this.editDatePickerInputCell)
        this.editDatePickerInputCell.nativeElement.focus();
    },500); 
  }

#sample object being passed when cell is clicked

{
    "id": 99,
    "transactionId": 13517,
    "name": "",
    "isHeaderCategory": false,
    "isRequired": true,
    "order": 3,
    "editing": true
}

Answer №1

Opt for a variable instead of using "data.editing"

indexEditing:number=-1;

So, you can do the following:

  <!--check against indexEditing-->
  <mat-form-field *ngIf="indexEditing==index && 
               selectedCell === 'sunsetDate'; else viewSunsetDate">
      ...
  </mat-form-field>

In your function:

editDateTest(value:EntitlementTransactionTemplateDto,index:number, columnName: string){
   this.indexEditing=index;
   ...
}

When you finish editing, simply:

dateChange(...){
  this.indexEditing=-1;
  ...
}

(*) If you have a *ngFor loop, just use:

<ng-container *ngFor="let data of yourList; let index=index">
</ng-container>

If you're working with mat-table, make sure to utilize:

<td mat-cell *matCellDef="let element; let index = index;">
...
</td>

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

Displaying items in pairs in AngularJS with ng-repeat

The design I want to achieve is as follows: <div> <div class="row"> <div></div> <div></div> </div> <div class="row"> <div></div> <div></div> ...

Tips for verifying the contents of a textbox with the help of a Bootstrap

I am still learning javascript and I want to make a banner appear if the textbox is empty, but it's not working. How can I use bootstrap banners to create an alert? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&g ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

javascript: Retrieve specific row data from Bootstrap Modal table and pass it back to the main webpage

I am a beginner in using bootstrap modals and JavaScript, and I need assistance in resolving the following issue. Desired Outcome: 1. When the parent screen opens the modal window, it should display a form to find a username: <div class="form-gro ...

The power of negative multiplication in TypeScript and React

I am working with a state variable called sortDirection const [sortDirection, setSortDirection] = useState<1 | -1>(1); My goal is to allow a button to toggle the state variable like this setSortDirection(sortDirection * -1); However, I encounter a ...

Retrieve JSON data with Bootstrap Typeahead for both ID and Value

To enable autocomplete for the typeahead feature, I want it to work specifically with the name field. When an item is clicked, I need it to collect the corresponding id value. $('.autocomplete').typeahead({ source: function (query, process) ...

Version 1.0 of the Angular 4 branch integrated with Auth0 JWT

I have been trying to implement the code provided on this website https://github.com/auth0/angular2-jwt/tree/v1.0 However, I am facing an issue with the following code snippet that needs to be placed in the app.module.ts file. The problem is that this co ...

Using a function to identify and check dynamically added checkboxes

I am using a PHP page that loads a group of categories from another PHP script as checkboxes. Here is the format for the checkboxes: <input type='checkbox' class='cat-selector' id='Business' data-toggle='checkbox&apo ...

Sliding out list elements with jQuery ladder effect

I'm stuck on a seemingly simple task and need some guidance. facepalm. Currently, my site at this link has a menu list item issue where they all come out from the left side after the picture loads. I want them to slide out one by one, starting from t ...

How can I create a fading trail effect in Three.js that diminishes over time?

I am interested in achieving a similar effect to the example I found on this website: However, my goal is to have the old trail gradually fade into the background over time instead of cluttering the screen with persistent marks. I discovered that by usin ...

Executing the `process.nextTick` function throws an error, causing the message: "Headers cannot be set once they have been sent."

I'm attempting to retrieve data from MongoDB within a Node.js file. I am encountering the following error: /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:98 process.nextTick(function() { throw err; }); Error: Can't ...

Using JavaScript, locate the previous and next elements in the JSON array of objects based on the given current event ID

Task: To retrieve and display data based on the current event ID from a JSON file: var _getEventById = function(eventId) { var __findEvent = function(event) { return event.id === eventId; }; return _.find(data.meeting ...

JavaScript function executes before receiving AJAX response

Within my code, there is an AJAX function named flagIt() that gets triggered by another function called validateForm() upon submission. The validateForm() function is responsible for form validation. function validateForm(){ var error = ""; //perf ...

Unable to locate element using document.getElementById in ASP.NET form

Currently, I am working on a project to create an ASP.NET webforms page that will showcase a Google map using the Google Maps JavaScript API with multiple markers. Everything is functioning smoothly as long as I don't place <div id="map-canvas"> ...

AngularJS facing difficulty in resolving the returned promise

I am facing an issue with two cascading drop-downs where the JSON data being returned to the second drop-down is not rendering properly due to a promise resolution problem <div class="row" style="padding-bottom:50px;width:85%;"> <select data ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

jQuery's element loading function fails to work with ajax requests

When trying to preload ajax data before attaching it to a div, I utilized the following code: $.ajax({ url: 'ajax.php', data: { modelID:id }, type: 'post', success: function(result){ $(result).load(function(){ ...

Error in Angular Apollo V3: Jest unable to locate module 'apollo-angular'

After recently updating angular apollo from version 2.6.0 to v3.0.0, my tests have been broken. I use jest for unit testing, and although the application compiles and runs without any issues, my tests cannot import any dependencies from 'apollo-angul ...

"PHP: Are you sure you want to delete? Confirm your

I'm trying to add a delete account button on my website, but I'm struggling with the implementation. Here's what I have so far: Javascript: <script language = "JavaScript" > function deleteUser(id) { if (confirm ...