首页 > 解决方案 > 切换用户可以删除文本框中的文本与不删除文本的状态

问题描述

我的应用程序中有一个复选框。当用户选中复选框时,我需要我的 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", "")
  }

但这不起作用,因为当用户选中然后取消选中时,他们无法再次输入。

我怎样才能解决这个问题?谢谢!

标签: javascriptjqueryangular

解决方案


这是一个适合你的堆栈闪电战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>

推荐阅读