[英]Strange behavior on editable div when trying to update a variable with text content in an editable div in angular. Any explanations?
I am trying to create a text editor and have created a custom element in angular using an editable div.我正在尝试创建一个文本编辑器,并使用可编辑的 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.在某些情况下,我将不得不为 div 的内容设置一些初始值,并在某些情况下捕获 div 中的输入数据。
But I am getting three different behaviors for the same div based on the initial value that is set.但是我根据设置的初始值为同一个 div 获得了三种不同的行为。
I want the div to behave like a regular input field but I don't want to use the actual Input element.我希望 div 表现得像一个常规输入字段,但我不想使用实际的 Input 元素。
I have made a working example of the problem in the Stackblitz demo .我在Stackblitz 演示中制作了一个问题的工作示例。
The components code is as below.组件代码如下。
The template HTML for the element component:元素组件的模板 HTML:
<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: CSS:
div{
background: black;
margin: auto;
color:white;
font-size: 2em;
}
The three different behaviors are:这三种不同的行为是:
I am expecting the 3rd behavior, in example after you clear the element the way it behaves.我期待第三种行为,例如在您按照元素的行为方式清除元素之后。
Possible explanation: You haven't declared the bound value.可能的解释:您尚未声明绑定值。
Workaround: Adding:解决方法:添加:
[textContent]="model"
when declaring template div
[textContent]="model"
声明模板div
model;
ngOnInit(){
this.model = this.value;
}
inside ElementComponent
export class在ElementComponent
导出类中
Related: How to use [(ngModel)] on div's contenteditable in angular2?相关: 如何在 angular2 中的 div 的 contenteditable 上使用 [(ngModel)]? , https://github.com/KostyaTretyak/ng-stack/tree/master/projects/contenteditable , https://github.com/KostyaTretyak/ng-stack/tree/master/projects/contenteditable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.