Angular 2 Material Input change placeholder dynamically

Viewed 37691

I want to change the text of the input placeholder dynamically. The console.log already gives the updated string but the interface doesn't update so there stays the old placeholder. How can I get the Interface to recognize the change?

document.getElementById(this.implicKey).setAttribute('placeholder', options[i].implication);

console.log(document.getElementById(this.implicKey).getAttribute('placeholder'));
4 Answers

We can do that using property binding.

In the HTML, use square brackets:

<input formControlName="events" type="text" [placeholder]="newPlaceHolder">

In your typescript file, define the property:

newPlaceHolder: string = "original place holder";

Then, change the property value:

newPlaceHolder= "my new place holder";

This one works great for me:

(I use it to show dynamic error on mat-autocomplete form field)

on your HTML:

 [placeholder]="isPlaceHolderShowError('myFormControlName')"

on your TS:

    isPlaceHolderShowError(myFormControlName) {
    if (this.form.controls[myFormControlName].invalid && this.form.controls[myFormControlName].touched) {
      return 'this is my error text'
    }
    return 'this is the initial placehloder'
  }

another option may be in the HTML, use square brackets whith attribute binding:

<input formControlName="events" type="text" [attr.placeholder]="newPlaceHolder">

In your typescript file, define the property:

newPlaceHolder: string = "text binding" 
Related