以编程方式更新[占位符]反应性表单控件 [英] Updating [placeholder] Reactive Form Control Programmatically

查看:50
本文介绍了以编程方式更新[占位符]反应性表单控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为响应式表单的一部分,我具有以下formControl:

<input class="input" formControlName="email" [placeholder]="">

我想知道是否可以通过编程方式设置占位符?

类似的东西:this.formGroup.get('email').placeholder = 'Some value';

解决方案

placeholder是HTML元素本身的属性,而不是formGroup.您可以像使用组件属性([placeholder]="someValue")一样直接绑定它,并且Angular的更改检测将自动更新它.

您还可以通过@ViewChild抓取元素本身,并将其更新为元素的属性(即Vanilla JS):

<input #myInput />

// ...

@ViewChild('myInput') myInput: ElementRef;

// ...

myInput.nativeElement.placeholder = 'New Thing';

如果您对这些占位符有某种标准化的行为,则可以将其外推到Directive中,从而以更简洁的方式完成此行为.

I have the following formControl as part of my Reactive Form:

<input class="input" formControlName="email" [placeholder]="">

I was wondering if there were a way to set the placeholder programmatically?

Something like: this.formGroup.get('email').placeholder = 'Some value';

解决方案

The placeholder is a property of the HTML element itself, not the formGroup. You can directly bind it like you're doing with a component property ([placeholder]="someValue") and Angular's change detection will update it automatically..

You can also grab the element itself via @ViewChild and update it as a property of the element (i.e. vanilla JS):

<input #myInput />

// ...

@ViewChild('myInput') myInput: ElementRef;

// ...

myInput.nativeElement.placeholder = 'New Thing';

If you have a somewhat normalized behavior for these placeholders, you can even extrapolate this into a Directive that accomplishes this behavior in a cleaner way.

这篇关于以编程方式更新[占位符]反应性表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆