在patchValue或setValue之后,Angular FormGroup不会立即更新它的值

时间:2017-06-13 13:54:11

标签: javascript angular typescript angular2-forms

我的表格如下:

 createForm() {
    this.procedimentoForm = this.formBuilder.group({
      nome: ['', Validators.required],
      descricao: ['', Validators.required],
      conteudo: ['', Validators.required],
      solucao: ['', Validators.required],
      mesa: ['', Validators.required]
    });
  }

模板:

<form [formGroup]="procedimentoForm" class="ui form">
  {{procedimentoForm.value.conteudo}}


  <div class="field">
    <label>Descrição</label>
    <input type="text" placeholder="Descrição" formControlName="descricao">
  </div>

  <div class="field">
    <label>Conteúdo</label>
    <tinymce [elementId]="'conteudo'" (onEditorKeyup)="keyupHandlerFunction($event)"></tinymce>
  </div>

</form>

它使用实现TinyMCE编辑器的自定义组件:

import { Component, AfterViewInit, ViewChild, EventEmitter, forwardRef, ElementRef, OnDestroy, Input, Output } from '@angular/core';
import { 
ControlValueAccessor, 
NG_VALUE_ACCESSOR, 
NG_VALIDATORS, 
FormControl, 
Validator 
} from '@angular/forms';

@Component({
selector: 'tinymce',
templateUrl: './tinymce.component.html',
})
export class TinyMCEComponent implements AfterViewInit, OnDestroy {
@Input() elementId: String;
@Output() onEditorKeyup = new EventEmitter();

editor;

ngAfterViewInit() {
    tinymce.init({
        selector: '#' + this.elementId,
        plugins: ['link', 'paste', 'table'],
        skin_url: '../assets/skins/lightgray',
        setup: editor => {
            this.editor = editor;
            editor.on('keyup', () => {
                const content = editor.getContent();
                this.onEditorKeyup.emit(content);
            });
        }
    });
}

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

}

表单中的keyup处理程序如下所示:

keyupHandlerFunction(event) {
    console.log(this.procedimentoForm);
    this.procedimentoForm.markAsDirty()
    this.procedimentoForm.patchValue({ conteudo: event }, {onlySelf: false, emitEvent: true});
    console.log(this.procedimentoForm.value.conteudo);
  }

问题是,我可以看到this.procedimentoForm.value.conteudo正在改变,因为我在keyup事件处理程序中记录了“console.log(this.procedimentoForm.value.conteudo)”。但是,{{procedimentoForm.value.conteudo}}在我将焦点从编辑器中更改之前不会更新。此外,在焦点更改之前,验证不会更新。我不明白为什么。

1 个答案:

答案 0 :(得分:2)

如果支持值正在更新,但更改未反映在视图中,则可能是因为它没有标记为更新。

您可以使用ChangeDetectorRef手动检测更改: https://angular.io/api/core/ChangeDetectorRef#!#detectChanges-anchor