user8398743
user8398743

Reputation:

Angular - Toggle Content

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
  }

Upvotes: 1

Views: 514

Answers (2)

Vega
Vega

Reputation: 28711

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

Upvotes: 0

Julio Bastida
Julio Bastida

Reputation: 1219

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.

Upvotes: 2

Related Questions