以编程方式从控制器更改[(ngModel)]绑定

时间:2017-04-16 08:21:23

标签: angular typescript

我正在尝试从控制器中更新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
}

Plunker

更新 如果我从textarea中删除display: none属性,我可以看到textarea元素的内容已更改,但其自身的属性settings.value尚未更新。

1 个答案:

答案 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'))
}