如何使用 Angular4 创建额外的占位符属性? [英] How can I create an additional placeholder attribute using Angular4?
问题描述
我在一个项目中使用 Angular Material.在该项目中,我有一个使用 autocomplete 组件的表单.一切正常 - 但是,我想在用户聚焦输入元素时添加占位符文本.
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 使用 placeholder 属性并在运行时将其转换为标签元素.我希望实际的占位符属性可以说我的占位符"以外的其他内容.
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屋!