How can I create an additional placeholder attribute using Angular4?

走远了吗. 提交于 2019-12-10 12:30:14

问题


I am using Angular Material on a project. Within that project I have a form that is using an autocomplete component. Everything is working well - however, I would like to add placeholder text when the user focuses the input element.

Here is my html template:

<input type="search" matInput placeholder="My Placeholder"
     aria-label="My Placeholder"
     [matAutocomplete]="mySearch"
     [formControl]="myCtrl"
     (focus)="onInputFocus()"
     [(ngModel)]="myModel">

within my .ts file, I have this method:

public onInputFocus(event: Event): void {
    // do stuff
}

Angular Material uses the placeholder attribute and turns that into the label element at runtime. I would like the actual placeholder attribute to say something else other than "My Placeholder".

For example, if a user clicks into the input, "My Placeholder" moves up, and the word "Search" shows as the placeholder text.

I have considered using css to set a background image, or create a custom data attribute. Or within the .ts file dynamically create ?? to show placeholder text. Has anyone else run into this issue?

Thank you for any suggestions!


回答1:


You can bind to placeholder like this

<input type="search" matInput [placeholder]="placeholderText">

And then in your class,

placeholderText = 'My Placeholder';

updatePlaceholderText() {
  this.placeholderText = 'Search';
}



回答2:


Thank you, @Will Howell - that got me headed down the right path I think. What I ended up doing was adding a new attribute "real-placeholder" & manipulating that.

template.html

<input type="search" real-placeholder="Search" placeholder="My Placeholder"
(focus)="onInputFocus($event)" (blur)="onInputBlur($event)">

component.ts

/**
* Input focus event listener.
* @param {Event} event
*/
public onInputFocus(event: HTMLSelectElement): void {
    const placeholder = event.target.getAttribute('real-placeholder');
    event.target.setAttribute('placeholder', placeholder);
}

/**
* Input blur event listener.
* @param {Event} event
*/
public onInputBlur(event: HTMLSelectElement): void {
    event.target.setAttribute('placeholder', '');
    if (event.target.value !== '') {
        event.target.setAttribute('style', 'opacity:1;');
    }
}

component.scss

[real-placeholder] {
    opacity: 0;
    -webkit-transition: opacity 0.4 ease-in-out;
    transition: opacity 0.4 ease-in-out;

    &:focus {
        opacity: 1;
    }
}

The above will place the word "Search" in the input area like a traditional html placeholder attribute. I added some nicer css to have the "Search" fade in vs. snap on/off.

Hope this helps someone else!



来源:https://stackoverflow.com/questions/47042584/how-can-i-create-an-additional-placeholder-attribute-using-angular4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!