如何使用Angular4创建其他占位符属性? [英] How can I create an additional placeholder attribute using Angular4?
问题描述
我在一个项目上使用 Angular Material .在该项目中,我有一个使用自动完成组件的表单.一切工作正常-但是,我想在用户将输入元素放在焦点上时添加占位符文本.
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.
这是我的html模板:
Here is my html template:
<input type="search" matInput placeholder="My Placeholder"
aria-label="My Placeholder"
[matAutocomplete]="mySearch"
[formControl]="myCtrl"
(focus)="onInputFocus()"
[(ngModel)]="myModel">
在我的.ts
文件中,我有以下方法:
within my .ts
file, I have this method:
public onInputFocus(event: Event): void {
// do stuff
}
Angular Material使用占位符属性,并在运行时将其变为label元素.我希望实际的占位符属性说我的占位符"以外的其他内容.
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.
我已经考虑过使用CSS设置背景图像或创建自定义数据属性.还是在.ts
文件内动态创建??显示占位符文本.还有其他人遇到这个问题吗?
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?
谢谢您的任何建议!
推荐答案
谢谢@Will Howell-我朝正确的道路前进. 我最终要做的是添加一个新属性"real-placeholder"&操纵它.
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;
}
}
以上内容将把搜索"一词放置在输入区域中,就像传统的html占位符属性一样.我添加了一些更好的CSS,以使搜索"淡入淡出与快照打开/关闭.
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!
这篇关于如何使用Angular4创建其他占位符属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!