簡體   English   中英

如何從 Javascript 設置 Angular formcontrol 字段的值?

[英]How can I set the value of an Angular formcontrol field from Javascript?

我的表單組中有一個“敘述”字段。 我已將Nanospell Javascript 拼寫檢查器添加到我的項目中。

如果有拼寫錯誤的單詞並且我讓拼寫檢查器更改它們,拼寫檢查器會執行其工作並將更正后的文本字符串寫入window.form1.narrative.value 但是,除非我在拼寫檢查完成后在該字段中實際鍵入或退格一個附加字符,否則底層的 formcontrol 值仍然是以前拼寫錯誤的單詞的值。 任何用戶都不會這樣做。 拼寫檢查完成后,他們將單擊“保存”。 拼寫檢查器有一個onDialogComplete Javascript 函數。

如何使用該 Javascript 函數將文本框中的更新值設置為 formcontrol 值,以便保存拼寫正確的文本?

這是一個完整的 Angular 解決方案,可以讓這一切發生:-)

import { Component, OnInit, Input, OnDestroy, AfterViewInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { EditorFieldInfo } from '@app/shared/models/editorfieldinfo';

import 'tinymce';
declare let tinymce: any;

@Component({
  selector: 'rich-text-field',
  templateUrl: './rich-text-field.component.html'
})
export class RichTextFieldComponent implements OnInit, OnDestroy, AfterViewInit {

  formControl: FormControl;

  editor: any;

  @Input()
  formGroup: FormGroup;

  @Input()
  fieldDefinition: EditorFieldInfo;

  constructor() { 
    this.fieldDefinition = { name: '??', description:'', placeholder:'', hint:'', fieldtype:'', length:0, defaultValue:'', listValues: null};      
  }

  ngOnInit(): void 
  {
    this.formControl = <FormControl> this.formGroup.get(this.fieldDefinition.name);         
  }
  
  ngAfterViewInit() { 

    let textAreaElement = 'mce-' + this.fieldDefinition.name;

    this.formControl.valueChanges.subscribe( _ => {
      tinymce.init({
        base_url: '/tinymce',
        suffix: '.min',
        selector: '#' + textAreaElement,
        toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | outdent indent',
        menubar: 'edit insert format table tools', branding: false, placeholder: '',
        external_plugins: {'placeholder': '/assets/scripts/placeholder.min.js'},
        content_style: 'body {font-weight: 400;line-height:1.125;font-family:RO Sans,Calibri,sans-serif;letter-spacing:normal;}',
        setup: editor => { 
          this.editor = editor; 
          editor.on('change', _ => this.formControl.setValue(editor.getContent()));                      
        }
      });  
    });

  }

  ngOnDestroy() {
    tinymce.remove(this.editor);   
  }
}

您必須像這樣顯式更新FormGroup FormControl的值:

this.{your_FormGroup_name}.get('{your_FormControl_name}').setValue('some_value');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM