javascript - 切换用户可以删除文本框中的文本与不删除文本的状态
问题描述
我的应用程序中有一个复选框。当用户选中复选框时,我需要我的 textarea 填充无法删除的文本。他们可以添加到文本中,但不能删除它。
所以如果字符串是Hello my name is
,我想将它添加到 textarea 并且他们不能删除但他们只能添加他们的名字。
但是,如果他们取消选中该复选框,我需要删除文本Hello my name is
,并且只允许用户键入他们想要的任何内容。我正在努力解决如果他们选中复选框并再次取消选中他们能够输入的部分......
这是我所拥有的:
addHelloMyNameIs(val) {
let message = "Hello my name is";
let isChat = val; // val is true or false
var readOnlyLength = message.length;
console.log(isChat)
this.postTextarea = message + this.postTextarea;
$('#newPostTextarea .text-input').on('keypress, keydown', function(event) {
if(isChat) {
if ((event.which != 37 && (event.which != 39)) &&
((this.selectionStart < readOnlyLength) ||
((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
event.preventDefault();
}
}
});
}
cancelHelloMyNameIs() {
this.addHelloMyNameIs(false)
this.postTextarea = this.postTextarea.replace("Hello my name is ", "")
this.postTextarea = this.postTextarea.replace("Hello my name is", "")
}
但这不起作用,因为当用户选中然后取消选中时,他们无法再次输入。
我怎样才能解决这个问题?谢谢!
解决方案
这是一个适合你的堆栈闪电战https://stackblitz.com/edit/angular-nd7srq
这是一个极简示例,因此您可以清楚地看到正在发生的事情并可以复制任何相关位。
代码如下:
import { Component, ViewChild } from '@angular/core';
const START = 'Hello my name is '
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
checked = false;
taContent = '';
checkChanged() {
if (this.checked) {
this.taContent = START + this.taContent;
} else {
this.taContent = this.taContent.split(START)[1];
}
}
taChanged(txt) {
if (this.checked) {
if (txt.startsWith(START)) this.taContent = txt;
else {
const tmp = this.taContent;
this.taContent = '';
setTimeout(() => {
this.taContent = tmp;
})
}
} else {
this.taContent = txt;
}
}
}
HTML:
<br>
<input type="checkbox" [(ngModel)]="checked" (change)="checkChanged()">
<br>
<br>
<textarea [ngModel]="taContent" (ngModelChange)="taChanged($event)">
</textarea>
推荐阅读
- c++ - 如何在 C++ 中从 R 包调用 R 函数、存储结果并在 C++ 中使用它以进行进一步处理
- java - 为什么在 weblogic 上部署时出现模块异常错误?
- python-3.x - 有没有办法查看 Jupiter Notebook 中的 NLTK 或 Keras 函数?
- python - 安装 gnuradio 并缺少依赖项
- python - 如何在 Docker Compose 中将 Scrapy 与 Python 和 Tor over Privoxy 一起使用
- excel - Excel 中的多个参数
- java - 是否有一种快速的反射字段访问方法?
- postgresql - 尝试在 azure 云提供商上创建私有链接时出现问题
- python - 如何从 cython 访问 python 共享内存?
- c++ - 如何在初始化时设置结构的向量成员的大小?