【问题标题】:Dropdown value patch based on cursor position in textarea基于文本区域中光标位置的下拉值补丁
【发布时间】:2021-03-18 18:09:43
【问题描述】:

我有一个 textarea 和一个 dropdown。当我在 下拉列表 中选择一个值时 特定值将出现或被插入或添加到文本区域。因此,如果用户选择,则在键入 Dear 之后 一个名为 name 的 dropdown 值,它应该在文本区域中显示为亲爱的名字。我已经完成了,但是有一个错误

dropdown 值会根据光标所在的最大位置进行修补 当前光标位置。比如说你输入三个单词然后你把光标放在 在第一个单词附近并选择一个 dropdown 值,该值被修补在第三个单词的 en 上(最大位置) 当前光标位置的 我希望在当前光标位置上修补下拉值

HTML:

<textarea [(ngModel)]='textValue' rows="10" cols="70">
</textarea>
<div>
  <mat-form-field class="input-style">
    <mat-select (change)="changeValue($event)">
      <mat-option *ngFor="let li of list4" [value]="li">
        {{li}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</div>

Ts:

changeValue(ev) {
this.textValue += ` ${ev.value}`; }

知道的请帮忙

Stackblitz:https://stackblitz.com/edit/angular-mat-form-field-rjr5tu?file=app%2Fform-field-prefix-suffix-example.html

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    您需要考虑 textArea 的“selectionStart”和 selectionEnd。为此,创建一个模板引用变量并传递给函数

    <!--see the #text-->
    <textarea #text [(ngModel)]='textValue' rows="10" cols="70">
    </textarea>
    ...
        <!--pass the "variable" to the function changeValue-->
        <mat-select (change)="changeValue($event,text)">
          ...
        </mat-select>
    

    然后你的函数changeValue

      changeValue(ev,textArea:any) {
        const posInitial=textArea.selectionStart;
        const posFinal=textArea.selectionEnd;
        this.textValue = this.textValue.substr(0,posInitial)+
                         ev.value+
                         this.textValue.substr(posFinal);
      }
    

    注意:如果您不想将“文本”传递给函数,您也可以使用 ViewChild

    @ViewChild("text") textArea:ElementRef
    

    并使用

    获得职位
    const posInitial=this.textArea.nativeElement.selectionStart;
    const posFinal=this.textArea.nativeElement.selectionEnd;
    

    看到在这种情况下你使用 this.textArea.ElementRef

    stackblitz

    【讨论】:

    • 你太快了,看看我用 stackblitz 更新的答案
    • 您的解决方案有效。为了便于理解,我在那个 stackblitz 中给了你一个示例函数。实际上,我有一个复杂的功能。当我尝试实施这个解决方案时,我得到了双倍的价值。你能在那个链接里更新一下吗?
    猜你喜欢
    • 2016-04-30
    • 2010-09-25
    • 1970-01-01
    • 2023-03-15
    • 2011-10-21
    • 2023-03-02
    • 2011-12-21
    • 1970-01-01
    相关资源
    最近更新 更多