Angular 2 Material Input change placeholder dynamically
Asked Answered
P

4

17

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'));
Polinski answered 1/6, 2017 at 12:36 Comment(1)
why are you using document.getElementById you can change using bindingLaser
L
26

you can change your input placeholder dynamically like this

<md-input-container class="demo-full-width">
                <input mdInput [(ngModel)]="firstname" placeholder="{{somePlaceholder}}" name="firstname" required>
                <md-error>This field is required</md-error>
            </md-input-container>

component.ts

somePlaceholder : string = "new value";

now you can change somePlaceholder value any where in the class.

Laser answered 1/6, 2017 at 13:51 Comment(1)
I added this function setPlaceholder(value: string) { this.somePlaceholder = value; } and passed it as a closure to my service so I can set the placeholder when data arrives. But it says this is undefined. What am I doing wrong? The service's subscribe happens inside the service class itself and I invoke the closure method onSuccess.Geology
B
5

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";
Bilbo answered 12/6, 2018 at 21:43 Comment(0)
R
1

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" 
Raffle answered 1/1, 2022 at 22:24 Comment(0)
H
0

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'
  }
Hopson answered 20/7, 2020 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.