I am trying to create a text editor and have created a custom element in angular using an editable div.
I will have to set some initial value to the content of the div in some cases and capture the typed data in the div in some cases.
But I am getting three different behaviors for the same div based on the initial value that is set.
I want the div to behave like a regular input field but I don't want to use the actual Input element.
I have made a working example of the problem in the Stackblitz demo.
The components code is as below.
The template HTML for the element component:
<div contentEditable='true' (input)="update($event)">{{value}}</div>
<p>{{value}}</p>
The typescript file for the component element:
import { Component, Input } from '@angular/core';
@Component({
selector: 'element',
template: `<div contentEditable='true' (input)="update($event)">{{value}}</div>
<p>{{value}}</p>
`,
styleUrls: ['./element.component.css']
})
export class ElementComponent {
@Input() value: string;
update(event) {
this.value = event.target.innerText;
}
}
The CSS:
div{
background: black;
margin: auto;
color:white;
font-size: 2em;
}
The three different behaviors are:
- If you do not set an initial value to the value input field, as you type in the div, the text gets appended to itself continuously.
- If you provide an initial value to the value input field, as you type in the div, the cursor resets it to the initial position.
- Whether you provide an initial text or you type something in the empty div, If you select all the text from the div and hit delete or backspace and start typing in it. It behaves as a normal textbox.
I am expecting the 3rd behavior, in example after you clear the element the way it behaves.