我正在尝试从控制器中更新ngModel的值而不实际编辑textarea中的值
<textarea [(ngModel)]="settings.value" #textarea
style="display: none;"></textarea>
<button (click)="openEditorDialog(settings.value, textarea)">
Edit Code
</button>
请注意,在这种情况下,我没有使用ReactiveFormsModule
,而是使用常规FormsModule
。在此方案中不能使用Reactive模块,因为在从服务器获取“蓝图”后动态生成输入
控制器
openEditorDialog(code: string, textarea: HTMLTextAreaElement): void {
...
// updating code through a dialog
// `updateCode` has the updated value correctly stored
...
// Trying to update the textarea's value in hope the binding would
// update for `settings.value` as well
textarea.value = updateCode
// tried with `cdr.detectChanges()` without success
}
更新
如果我从textarea中删除display: none
属性,我可以看到textarea
元素的内容已更改,但其自身的属性settings.value
尚未更新。
答案 0 :(得分:4)
经过一些摆弄并阅读源代码后,我发现我们可以在textarea
上手动触发更新事件,以使Angular获取更改
openEditorDialog(code: string, textarea: HTMLTextAreaElement): void {
// do stuff with code, assume it is now stored in `updateCode`
...
textarea.value = updateCode
// triggering the input event will make Angular pick up the changes
// made to the textarea by setting it's value
textarea.dispatchEvent(new Event('input'))
}