Guide to implement editable columns in Angular 4 with a click functionality

I have a table displaying records using ngFor, and I am looking to enable editing of a column upon clicking it.

<tr *ngFor="let cd of descriptionCodes; let i = index">
  <td><input type="checkbox"></td>
  <td>
    {{cd.code}}>
  </td>
  <td>
    <select class="form-control border-gray" id="codeType" [(ngModel)]="cd.codeType.id" (change)="onCodeTypeChange(i, cd.id)" [ngModelOptions]="{standalone: true}">
      <option *ngFor="let type of codeTypes" [ngValue]="type.id">{{type.name}}</option>
    </select>
  </td>
  <td>{{cd.description}}</td>
</tr>

I am aiming for the functionality where clicking on a code or description should make it editable. Also, I want only one field to be editable at a time, meaning that selecting another field should disable editing on the previously edited field.

Any suggestions would be greatly appreciated!

Answer №1

To indicate the status of a column, you should have a property that does so and then set it during the click event of the td element.

Here is an example code snippet:

<tr *ngFor="let cd of descriptionCodes; let i = index">
 <td><input type="checkbox"></td>
 <td (click)="setCodeEdit(i)">
   <span *ngIf="!cd.canEditCode">{{cd.code}}></span>
   <input *ngIf="cd.canEditCode" type="text" class="form-control"  />
 </td>
 <td>
   <select class="form-control border-gray" id="codeType" 
  [(ngModel)]="cd.codeType.id" (change)="onCodeTypeChange(i, cd.id)" 
   [ngModelOptions]="{standalone: true}">
  <option *ngFor="let type of codeTypes" [ngValue]="type.id">{{type.name}}
    </option>
   </select>
  </td>
  <td (click)="setDescEdit(i)">
   <span *ngIf="!cd.canEditDesc">{{cd.description}}></span>
   <input *ngIf="cd.canEditDesc" type="text" class="form-control"  />
 </td>
 </tr>

In the component's implementation:

setCodeEdit(index){
  this.descriptionCodes.forEach(t => t.canEditCode = false)
  this.descriptionCodes[i].canEditCode=true
}

setDescEdit(index){
  this.descriptionCodes.forEach(t => t.canEditDesc= false)
  this.descriptionCodes[i].canEditDesc=true
}

I trust this information proves beneficial!

Answer №2

To retain cell data, store properties like isedit or editable. Upon clicking on a cell, set isedit to true and insert a new tag within the cell with *ngIf="cell.isedit". Within this tag, include an input or select element. Perform specific actions upon change or blur events, such as setting isedit to false or sending an update request.

Answer №3

To start, you need to extract the checkbox value by:

Utilizing HTML

<tr *ngFor="let cd of descriptionCodes; let i = index">
  <td><input type="checkbox" (change)="checkboxFunction($event)"></td>
  <td>
      <input type="text" class="form-control" value="{{cd.code}}" [readonly]="readOnly" />
  </td>
  <td>
    <select class="form-control border-gray" id="codeType" [(ngModel)]="cd.codeType.id" (change)="onCodeTypeChange(i, cd.id)" [ngModelOptions]="{standalone: true}">
      <option *ngFor="let type of codeTypes" [ngValue]="type.id">{{type.name}}</option>
    </select>
  </td>
  <td>  <textarea type="text" class="form-control" value="{{cd.description}}" [readonly]="readOnly"></textarea>
</td>
</tr>

In your Typescript file:

Using TS

checkboxFunction(event){
   if(event.target.checked){
this.readOnly = 'true';
}
}

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

Angular 5 - Empty array containing objects has a length of zero

In my app.component.ts file, I have an array initialized to load objects in the onInit event: ngOnInit() { this.pages = []; } Within the ngOnInit event, I also have a setInterval method that evaluates an expression every few milliseconds: setInterval(() ...

Substitute a specific text within an array of strings using Angular 2

Currently, I am working with a string array that includes elements such as age, gender, and nationality. Specifically, I am interested in replacing the element "age" with "agexxxx". Do you know of any methods to accomplish this within an Angular framewor ...

Issue: The 'async' pipe was not found after updating to AOT and IVY

I recently upgraded my project to AOT compliance and ever since, I've been experiencing issues with the | async pipe in my HTML code. Here is an example of what my HTML looks like: <div *ngIf="(mySubscription$| async) != null"> //some ...

Error: Unable to Locate Module (Typescript with baseUrl Configuration)

Struggling to implement custom paths in my TypeScript project, I keep encountering the "webpackMissingModule" error due to webpack not recognizing my modules. I've attempted various solutions without any success. Any suggestions or ideas? Some packa ...

Is there an issue with the newline character ` ` not functioning properly in TypeScript when used with the `<br/>` tag?

Having trouble with using New Line '\n' ' ' in Typescript Here is an example of my typescript code: this.custPartyAddress = estimation.partyName + ',' + '\n' + estimation.partyAddress + ',' + ...

Adding a # before each routing path: A step-by-step guide

One key difference between Angular 1 and Angular 4 is that in Angular 1, the routing path always includes a "#" symbol, whereas in Angular 4, it does not. I believe there may be a way to configure this function based on what I observed in the ng-bootstrap ...

What is the best way to design a basic server component that has the ability to retrieve data in NextJS 13?

Exploring the world of NextJS, I am currently utilizing NextJS 13 with the new app directory instead of the traditional pages directory structure. Despite trying various methods to fetch data, none seem to be working as expected. The process should be stra ...

Embedding a component inside another layout component in Angular

I'm attempting to insert a component into another layout component using a service, but I can't seem to get it working. Here is my current layout structure: AppComponent | AppLayoutComponent | ------------------------------------- ...

Setting dynamic values for SASS mixins in Angular 2 with Ionic 2

In my SCSS file, I have created a mixin to generate a progress bar. @mixin progressBarMix($name, $size, $perc, $color, $colorBack) { .progressBarWrapper { &#{$name} { $sizeFill: $size / 100 * $perc; .progressBarEndFilled { b ...

The Node.js express seems to be unable to fetch the css and js files

Sharing my main.ts file in which I am facing issues with linking my css and js files. view image import express from 'express'; import {Request,Response} from 'express'; import expressSession from 'express-session'; import pat ...

Having trouble invoking the "done" function in JQuery following a POST request

I am currently working on a Typescript project that utilizes JQuery, specifically for uploading a form with a file using the JQuery Form Plugin. However, after the upload process, there seems to be an issue when trying to call the "done" function from JQue ...

Turn off the touch events system for Ionic 2 on the leaflet map's draw controller

Seeking guidance on how to disable data-tap functionality in Ionic 2 within a leaflet map div. Anyone familiar with this? In Ionic-v1, the solution involved adding data-tap-disabled="true" to the map container (ion-content). I recently integrated the lea ...

What is the proper method for typing unidentified exports that are to be used in TypeScript through named imports?

Currently, I am developing an NPM package that takes the process.env, transforms it, and then exports the transformed environment for easier usage. The module is structured like this: const transformedEnv = transform(process.env) module.exports = transf ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

What could be causing the error in the console when I try to declare datetime in Ionic?

I am just starting out with Ionic and Angular, but I seem to have hit a roadblock. The compiler is throwing an error that says: node_modules_ionic_core_dist_esm_ion-app_8_entry_js.js:2 TypeError: Cannot destructure property 'month' of '(0 , ...

Dealing with Angular CORS Problems While Sending Successive Requests

I am currently working with Angular 6 and my backend consists of a node API. Occasionally, I encounter a CORS issue while making HTTP GET requests every 5 seconds. const url = 'https://<removed>.com/api/v1/transactions/' + transactionI ...

Creating a regular expression to capture a numerical value enclosed by different characters:

export interface ValueParserResult { value: number, error: string } interface subParseResult { result: (string | number) [], error: string } class ValueParser { parse(eq: string, values: {[key: string] : number}, level?: number) : ValueParse ...

Setting up TypeScript to function with Webpack's resolve.modules

Imagine having a webpack configuration that looks like this: resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], modules: ['my_modules', 'node_modules'], }, You have a ...

Turn off integrity verification for local dependencies in package-lock.json

Is there a way to bypass the integrity check for a local dependency in package-lock.json? Within my project repository, I have a core library along with two Angular applications that both rely on this core library as a dependency. The problem arises beca ...

Splitting the div into two columns

I've encountered various solutions to this issue, but when I integrate an Angular2 component inside the divs, it fails to function properly. Here is my progress so far: https://i.stack.imgur.com/qJ8a9.jpg Code: <div id="container"> <div ...