Home > Software design >  Angular read onblur placeholder value from a variable instead of hardcoding it
Angular read onblur placeholder value from a variable instead of hardcoding it

Time:09-30

In Angular html, I have an input field as:

<input id="yy" name="yy" type="text" placeholder="{{ product }}"
         onfocus="this.placeholder = ''"
         onblur="this.placeholder = 'xxx'">

With this when I take the mouse out of the input box, it shows placeholder value as xxx which is good

However, instead of hardcoding 'xxx', I want to read it from a variable defined in the component.ts

product = 'xxx'

In the template, I tried:

onblur="this.placeholder = {{product}}"

but that does not work. I tried a few other things but they dont work

Any idea how to set that placeholder value on blur with a variable instead of hardcoding a value there?

CodePudding user response:

<input
  id="yy"
  name="yy"
  type="text"
  placeholder="{{ product }}"
  (focus)="this.placeholder = ''"
  (blur)="this.placeholder = product"
/>

should work fine. but this is manipulating some placeholder property on the component, not the placeholder of the input. you're not thinking about this in an angular fashion if you're trying to set the placeholder of the input.

you probably are trying for a set up like this: https://stackblitz.com/edit/angular-9-starter-rwj1za?file=src/app/app.component.html

CodePudding user response:

you can try to use template variable:

<input id="yy"
       name="yy"
       type="text"
       #inputRef
       [placeholder]="product"
       (focus)="inputRef.placeholder = ''"
       (blur)="inputRef.placeholder = product"/>

CodePudding user response:

As an alternative solution, you can do this with just HTML/CSS and I find it cleaner, less JS in your component related to style/UI stuff.

This just takes away the placeholder (via font-size: 0) when you're focused on the input. Probably many different css properties you could use to achieve this but font-size does the trick for me.

<input 
  id="yy" 
  name="yy" 
  type="text" 
  placeholder="{{ product }}"
  class="input-test" />
.input-test:focus::placeholder {
  font-size: 0;
}

CodePudding user response:

User, you need change the variable "product", not this.placeholder. (Not exist nothing like this.placeholder). So you need two variables

You can, e.g. to have two variables "product" and "placeholder

<input id="yy" name="yy" type="text" 
    [placeholder]="placeholder"
    (focus)="placeholder=''"
    (blur)="placeholder=product">

Or two variables "product" and "isOnfocus" and use the conditional operator

<input id="yy" name="yy" type="text" 
    [placeholder]="isOnFocus?'':product"
    (focus)="isOnFocus=true"
    (blur)="isOnFocus=false">

NOTE: in Angular you use (focus) and (blur)

  • Related