问题描述
我有以下 formControl
作为我的响应式表单的一部分:
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?
类似:this.formGroup.get('email').placeholder = 'Some value';
推荐答案
placeholder
是 HTML 元素本身的属性,而不是 formGroup
.您可以像使用组件属性一样直接绑定它 ([placeholder]="someValue"
),Angular 的更改检测将自动更新它..
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..
您也可以通过 @ViewChild
获取元素本身并将其更新为元素的属性(即 vanilla JS):
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.
这篇关于以编程方式更新 [占位符] 反应式表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!