[英]Dropdown value patch based on cursor position in textarea
我有一個textarea和一個dropdown 。 當我 select下拉列表中的值時,特定值將出現或插入或添加到文本區域。 因此,在輸入 Dear 之后,如果用戶選擇了一個名為 name 的下拉值,它應該在文本區域中顯示為 Dear Name。 我已經做到了,但是有一個錯誤
下拉值根據 cursor 的最大位置進行修補,而不是當前的 cursor position。 say for example you type three words and you place the cursor near the first word and select a dropdown value the value gets patched on the en of third word(maximum position) instead of the current cursor position I want the dropdown value to be patched on當前 cursor position
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
您需要考慮 textArea 的“selectionStart”和 selectionEnd。 為此,創建一個模板引用變量並傳遞給 function
<!--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>
然后你的 function 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);
}
注意:如果您不想將“文本”傳遞給 function,您也可以使用 ViewChild
@ViewChild("text") textArea:ElementRef
並使用
const posInitial=this.textArea.nativeElement.selectionStart;
const posFinal=this.textArea.nativeElement.selectionEnd;
看到在這種情況下你使用 this.textArea.ElementRef
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.