2017-06-13 47 views
0

我有一個表格如下圖所示:角FormGroup不會更新它的patchValue後立即值的setValue

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); 
    } 

的問題是,我可以看到,因爲我日誌「的console.log是this.procedimentoForm.value.conteudo正在改變(this.procedimentoForm.value。 「在keyup事件處理程序中。但是,{{procedimentoForm.value.conteudo}}不會更新,直到我將焦點從編輯器中移出。此外,驗證不會更新,直到焦點更改。我看不出爲什麼。

回答

1

如果支持值正在更新但更改沒有反映在視圖中,很可能它沒有被標記爲更新。

可以使用ChangeDectorRef手動檢測更改: https://angular.io/api/core/ChangeDetectorRef#!#detectChanges-anchor

+0

是。在keyup處理程序中使用detectChanges()完成了這項工作。儘管我不清楚發生了什麼以及爲什麼patchValue不會更新視圖,但您的答案可以解決問題。謝謝。 – Alaor

+0

我想你錯過了你的例子中的一些代碼(它不清楚'procedimentoForm'是什麼),所以很難進一步詳細說明它爲什麼不能像你所顯示的那樣工作。 – Askanison4

+0

對不起。我用創建表單的代碼更新了問題。 – Alaor