1

I am using Angular 4 and I am trying to toggle contenteditable="true" / contenteditable="false"

I've got this:

<h1 (dblclick)="edit($event)" contentEditable="true">Double-click Here to edit</h1>

or I could also have a checkbox if its easier to toggle edit mode?

<input type="checkbox" name="" value="" (onchange)="edit($event)">Toggle Edit mode

and on the .ts file:

edit(event) {
    // code here needed
  }
2
  • How you are going to edit in a <h1> tag? Commented Aug 17, 2017 at 22:04
  • @Vega with the contentEditable attribute Commented Aug 17, 2017 at 22:10

2 Answers 2

2

Create a one way binding from the contentEditable property to a field in your Component, then add an event binding for the click event on the header.

In your component, create a boolean:

private isEditable = false;

Then, in your html, toggle the value of this boolean with a click event, and bind the contentEditable property to this boolean as well:

<h1 (dblclick)="isEditable = !isEditable" [contentEditable]="isEditable">

You could also put the code of the (dblclick) binding inside a method on your component, if you'd rather have some method like toggleIsEditable(), with additional logic.

Sign up to request clarification or add additional context in comments.

3 Comments

I am not sure this works, as the the editing mode is triggered on a simple click.
@Vega it works for what the OP was technically asking, but you are right that having to double click the element to turn on editable mode, then click again to edit is a weird behavior. Would work like this, though: <h1 (click) = "isEditable = true" (blur) = "isEditable = false [contentEditable]="isEditable" >. Here's your plunker with this implementation: embed.plnkr.co/41u12Nu4vpXpKPtcZzEN
Of course, all of this is assuming that the element need only be editable, not that the value of the element be stored in the component. If that were the case, a much more Angularly way to do this would be [(ngModel)].
0

What you need is the following.

HTML

<h4 (dblclick)="contentEditable=true; toto.focus()"
    *ngIf="!contentEditable">
  {{myText}}
</h4>
<input #toto
       autofocus
       *ngIf="contentEditable"
       [value]="myText"
       (keyup.enter)="contentEditable=false; save(toto.value)"
       (blur)="contentEditable=false; save(toto.value)"
       type="text">

TypeScript

myText = "Double-click Here to edit";

With some css you can get to have one in place of the other.

Here is the plunker

5 Comments

Its a good idea but when you double click the input is empty and what you type is not changed. Do I need to add code to the .ts file?
Thanks a lot for your time
The text is not changed after you blur
It does'nt need to save anyway just to retain the new value after blur
I did update the plunker to retain the value after the blur or enter key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.