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

bor*_*mke 3 typescript angular

我正在尝试从控制器内更新 ngModel 的值,而不实际编辑 textarea 内的值

<textarea [(ngModel)]="settings.value" #textarea
          style="display: none;"></textarea>

<button (click)="openEditorDialog(settings.value, textarea)">
    Edit Code
</button>
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下我没有使用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
}
Run Code Online (Sandbox Code Playgroud)

普朗克

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

bor*_*mke 6

经过一番摆弄和阅读源代码后,我发现我们可以手动触发更新事件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'))
}
Run Code Online (Sandbox Code Playgroud)