html - How to trigger a change event on a textarea when setting the value via ngModel Binding
问题描述
I have a <textarea>
within a template driven form of an Angular 7 project.
When editing an object, the form is prefilled with the current values. I want to automatically resize the <textarea>
when the content has changed via the [(ngModel)]="property"
binding by modifying the element-style.
area.style.overflow = 'hidden';
area.style.height = '0';
area.style.height = area.scrollHeight + 'px';
The code generally is working, but I cannot find a suitable event to trigger it.
Subscribing to the change
event of the <textarea>
is only working on keyboard input. Using (ngModelChange)="adjustTextAreaSize($event)"
has the same behavior.
I tried to execute my resizing code at the end of the ngOnInit()
function, but the actual html-control seems to not have any content yet at this point.
Does anyone have an idea which event could do the trick here? Seemed a rather easy task in the beginning, but I'm breaking my had over this for over an hour now... can not be such a difficult task, can it?
解决方案
是的,有一个非常简单的解决方案。将您的textarea
内部包裹起来form
并尝试以下代码:-
HTML
<form #form="ngForm">
<textarea>....</textarea>
</form>
TS
@ViewChild('form') ngForm: NgForm;
ngOnInit() {
this.subscription = this.ngForm.form.valueChanges.subscribe(resp =>
{
console.log(resp); // You get your event here
}
)
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
推荐阅读
- rest - 仅用于测试 REST 请求的 http 站点?
- hangouts-chat - Google Hangouts Chat API IP 加入白名单?
- python - 如何在 pyspark 中将 Dataframe 转换为 RDD?
- ios - 将 NSLocationAlwaysUsageDescription 添加到 info.plist 的含义
- android - 如何将此 iframe 添加到我的应用程序的中心
- java - 使用 deploy 命令在 glassfish 上部署 maven 项目
- r - 具有连续比例的 R 堆积条形图
- azure-pipelines - PostSharp 5.1.9 - 在 linux 托管构建服务器 .net core 2 pos 上构建失败
- angular - 使用变量值创建指令
- java - 如何将一个点声明为对象争论之一?