angular - Angular Reactive Form - 从 HTML 手动更新 FormGroup
问题描述
我创建了一个角度组件,可在文本字段中插入文本或在当前插入符号位置输入。
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。
<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 的更新和验证。我该怎么做呢?
解决方案
推荐阅读
- android - 当我尝试使用凭证 api 直接保存时,我收到此错误消息
- rest - Marketo REST API - 批准使用 REST API 创建的自定义活动类型 - 611 系统错误
- r - R knit to PDF 无法正常工作并出现错误
- python - Python websocket asyncio 多次使用相同的连接
- c++ - ld:在 dmlc 中找不到架构 x86_64 的符号
- ruby-on-rails - How do I print out model data without printing the array?
- java - 如何在servlet之间共享结果数据并在jsp上显示?
- wpf - 为什么这个标签的内容没有居中?
- javascript - 单独编辑对象的属性,需要“编辑”框为每个属性动态打开
- java - 单次执行多次运行字节伙伴转换