Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating [placeholder] Reactive Form Control Programmatically

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';

like image 356
User 5842 Avatar asked Dec 24 '22 09:12

User 5842


1 Answers

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.

like image 79
joh04667 Avatar answered Feb 19 '23 06:02

joh04667