gpt4 book ai didi

angular - 表单控件 :setValue don't fire input event

转载 作者:太空狗 更新时间:2023-10-29 18:23:32 27 4
gpt4 key购买 nike

我有一个带有 notes 字段的表单,该字段由文本区域界定。

this.form = this.formBuilder.group({});
this.form.addControl('notes', new FormControl(''));

模板附加了一个autoresize指令。

<textarea formControlName="notes" autosize></textarea>

这样的指令会在用户每次更改其内容时调整文本区域的高度。

@HostListener('input')
public onChange(textArea: HTMLTextAreaElement): void {
const textarea = this.element.nativeElement.querySelector('textarea');
this.renderer.setStyle(textarea, 'overflow', 'hidden');
this.renderer.setStyle(textarea, 'height', 'auto');
this.renderer.setStyle(textarea, 'height', `${textarea.scrollHeight}px`);
}

但是,当我以编程方式更改 FormControl 的值时,不会触发 input 事件,并且不会相应地调整文本区域的大小。

this.form.controls['notes'].setValue('a new value'); // not firing events

我做错了什么?

最佳答案

您可以绑定(bind)到将在两个事件上触发的 ngModelChange 而不是 input:

@HostListener('ngModelChange') onNgModelChange() {
console.log('ngModelChange');
}

查看演示:https://stackblitz.com/edit/angular-basic-template-say51l?file=src%2Fapp%2Fautosize.directive.ts

关于angular - 表单控件 :setValue don't fire input event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51026422/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com