Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue.

Below is my JSON data:

data = [{
    'id':1,'name': 'mr.x',
  },{
    'id':2,'name': 'mr.y',
  },{
    'id':3,'name': 'mr.z',
  },{
    'id':4,'name': 'mr.a',
  }]

I am displaying this in the template.

<div *ngFor="let x of info; let i = index">
                            <div id="{{x.id}}">


                            <div id="{{x.id}}">
                                        </div>
                                        <span [contentEditable]="content" id="{{x.id}}" > {{x.name}}</span>

                                         <button id="edit" (click)="edit(x.id)">edit

                                         </button>

What I am trying to achieve is, for each span element where {{x.name}} is displayed, I want to be able to change that name. So, I have implemented the following function:

edit(id){

   this.content = true;

}

However, it's not working and nothing is editable. My current issues are how can I make it editable based on a click event and how can I get the value of the span to display changes, which need to be sent to the server for processing.

Link to my stack:

https://stackblitz.com/edit/angular-gdqxwx

Answer №1

To successfully implement this, you must generate a dynamic property using the index as a basis, such as PropertyName[i].

Code:

 hideElement = {}; // Define in the .ts file

Html:

<div *ngFor="let x of info; let i = index">
 <div id="{{x.id}}">
    <div id="{{x.id}}">
  </div>
 <span [hidden]="!!hideElement[i]" id="{{x.id}}"> {{x.name}}</span>
 <input [(ngModel)]='x.name' type="text" [hidden]="!hideElement[i]" />
 <button id="edit" [hidden]='hideElement[i]' (click)="hideElement[i]=true">edit </button>
 <button id="save" [hidden]='!hideElement[i]' (click)="hideElement[i]=false">save </button>
</div>

View a live demo here

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

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...

Retrieving information from nested JSON objects using JavaScript

I'm struggling with extracting data from a JSON array object. Despite trying to use Iterables & Iterators, I can't seem to grasp the concept. { '-LIDMHr69GLnq1Pyzt6o': { author_avatar: { image: 'https://lh3. ...

Expanding the functionality of express.Router

Can someone help me with how to extend the functionality of express.Router? I attempted the following: class Test extends express.Router() { }; However, I encountered an error when trying this in Express. Does anyone have a solution for this issue? ...

Leveraging angular-cli to compile a library that can be easily integrated into multiple projects

Let me provide some context: I set up an angular-cli (beta 17) project for my organization that includes multiple components I want to share with other Angular 2 projects within the organization. Initially, I kept it simple by using npm to install the Gi ...

Mongoose throws a "Possibly unhandled rejection" error when trying to use ContactList.insert as it is not a recognized function

Currently working on a small project using the MEAN stack, but encountering an issue with sending a post request where console.log displays an error. Error Message: Possibly unhandled rejection: {"data":"TypeError: ContactList.insert is not a function S ...

Angular 8 seems to be disregarding SetTimeout

When executing the following code snippet: this.logger.warn('start'); setTimeout(() => {},3000); delay(3000); this.logger.warn('start2'); The output displays enter image description here Blockquote: ngx-logger.js:596 2020-11-19T13 ...

Echo input and refresh on the current page upon submission

I am facing an issue with refreshing the page after submitting a form. I want to refresh the page so that the login attempt can be counted, but currently, the form is displayed without the page being refreshed to add to the count. This is my current code s ...

Encountering difficulties when attempting to upload to Google Cloud using a signed URL

Seeking help to troubleshoot why the video upload is not working as expected. I am able to successfully connect to my bucket using a signedURL, but when trying to upload the video, it's not functioning properly. const submitVideo = async () => { ...

Is it possible to upgrade just the rxjs version while keeping all other components at their current versions?

While working on my Angular 4 project, I encountered a problem when trying to use a WebSocket package from GitHub. After running npm install to upgrade the rxjs version, I faced errors. Even after attempting to upgrade just the rxjs version and running ng- ...

index.js file in npm package optimized for browser compatibility using Babel transpiler

Struggling to create and set up an npm package for use in browser environments, particularly with generating the index file. Currently have the testpackage linked to my test application using npm link in both project directories. The test application is c ...

Unsubscribe from the Event Listener in Node.js

In light of this inquiry (linked here), can the Listener be eliminated from within the callback function? To illustrate: let callback = function(stream) { if(condition) performAction(); else server.removeListener('connection', cal ...

Trouble arises when trying to load angular ui-bootstrap using require.js unless I change the name to ui.bootstrap

Code Overview: main.js: require.config({ paths: { 'uiBootstrap': '../lib/bootstrap/angular-bootstrap/ui-bootstrap-tpls.min' }, shim: {***}, priority: ['angular'], deps: ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

I encounter an issue when trying to declare an enum in TypeScript

At line 26 in my typescript file, the code snippet below shows an enum definition: export enum ItemType { Case = 'Case', Study = 'Study', Project = 'Project', Item = 'Item', } I am currently using Visual Stu ...

Issue with displaying content using v-show in a Nuxt.js menu

Struggling to create a mobile menu with Vue instance error The Nuxt Menu Component : <template> <header id="menu" class="menu-g"> <Nuxt-link to="/"><img src="~assets/logo.svg" alt=&qu ...

Attempt the axios request again if the response is null or missing

await axios .post( executeBatch, { headers: { "Content-Type": "application/json", "x-access-token": localStorage.getItem("token"), }, } ) .then( ...

React - utilizing dynamic properties using string values

I am facing a challenge in my test suite where I need to generate components with dynamic props. The desired components should look like this: <Button primary /> <Button secondary /> However, I am currently stuck at this point: [ &apos ...

Animate CSS with Javascript in reverse direction

Forgive me if this is a silly question, but I'm having trouble. I need a slide-in navigation menu for smaller screens that is triggered by JavaScript. Here is what I currently have: HTML <nav class="responsive"> <ul class="nav-list unstyl ...

efficiency of this algorithm

function checkSubset(array1, array2) { const set1 = new Set(array1); const set2 = new Set(array2); for (const element of set2) { if (!set1.has(element)) { return false; } } return true; } Can we consid ...