我创建了一个角度组件,用于将文本插入文本字段或在当前插入符号位置输入。
import * as $ from 'jquery';
import { Component, ElementRef, EventEmitter, HostBinding, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-special-character',
templateUrl: './special-character.component.html',
styleUrls: ['./special-character.component.scss']
})
export class SpecialCharacterComponent implements OnInit {
@Input('character') private character:string;
@HostBinding('class') @Input('class') classList: string = '';
@Output() inserted = new EventEmitter();
@Input('target') targetId: string;
constructor(
private readonly elementRef: ElementRef) {
}
insert(): boolean {
// is there a character to insert?
if (!this.character) return false;
// get the target field
const $target = $(this.targetId);
// allow for properties not in document class
const browserDocument: any = document;
if (browserDocument.selection) {
$target.focus();
const range = browserDocument.selection.createRange();
range.text = this.character;
} else {
// get the current state
const selectionStart = $target.prop('selectionStart');
const selectionEnd = $target.prop('selectionEnd');
const value = $target.val();
// set the new value
$target.val(`${value.substring(0, selectionStart)}${this.character}${value.substring(selectionEnd, value.length)}`);
// set the cursor
$target.prop('selectionStart', selectionStart + this.character.length);
$target.prop('selectionEnd', selectionStart + this.character.length);
}
// now return to the target field
$target.focus();
return false;
}
ngAfterViewInit() {
const $component = $(this.elementRef.nativeElement);
// clear the classes from the component
$component.removeClass();
// get the button component
const $button = $component.children().first();
// add the classes
$button.addClass(this.classList);
// get the character to insert (if it isn't set manually)
if (!this.character) this.character = $button.text();
}
ngOnInit() {
}
}
该组件的html更新一个文本区域。
<textarea class="form-control" formControlName="field1FillInTheGap" id="question" placeholder="eg. The capital of France is ___?"></textarea>
<app-special-character class="btn btn-secondary btn-xs" character="___" target="#question">?</app-special-character>
文本插入可以正常工作,但是在插入文本后,关联的FormControl不会自动更新。我想手动触发与文本字段关联的反应式FormControl的更新和验证。我该怎么做?