![](/img/trans.png)
[英]Control over Animation of Angular Material form-field Label/Placeholder
[英]Placeholder and label in Angular 2 Material
我想設置一個占位符,該占位符在用戶鍵入時消失,並且輸入標簽始終浮在輸入上方,就像在此代碼筆中一樣: https ://codepen.io/anon/pen/QjypdO
但是我不知道如何用最新的角材料來實現它。
更新
由於Angular Material尚不支持它,因此我實施了一種變通方法來模擬所需的行為:
HTML
<md-input-container [ngClass]="{ 'zip': zipPlaceholderActive }">
<input mdInput [placeholder]="Zip" [ngModel]="zipValue" (focus)="removeDefaultValue()">
</md-input-container>
打字稿:
removeDefaultValue() {
if (this.zipPlaceholderActive) {
this.zipValue = '';
}
this.zipPlaceholderActive = false;
}
CSS:
.zip .mat-input-element {
color: #999;
}
這是我最接近Codepen占位符示例的位置。 此示例也處理鍵盤事件,因此如果用戶刪除了所有字符,則占位符會返回,如果用戶再次開始鍵入,則占位符會消失。
ts:
food: string = "Enter a food name";
showPlaceholder: boolean = true;
removePlaceholder(){
if(this.food == "Enter a food name"){
this.food = "";
this.showPlaceholder = false;
}
}
viewPlaceholder(){
if(this.food == ""){
this.food = "Enter a food name";
this.showPlaceholder = true;
}
}
html:
<md-input-container>
<input mdInput placeholder="Favorite food"
[(ngModel)]="food"
[ngClass]="{'gray-text': showPlaceholder}"
(focus)="removePlaceholder()"
(keydown)="removePlaceholder()"
(blur)="viewPlaceholder()"
(keyup)="viewPlaceholder()">
</md-input-container>
css:
.gray-text{
color: #999999;
}
柱塞演示
如果您只想在字段為空且未聚焦時替換占位符(因此當它實際位於應占位符的位置時),可以使用CSS來實現:
:host /deep/ :not(.mat-focused) .mat-input-placeholder.mat-empty {
color: transparent;
}
:host /deep/ :not(.mat-focused) .mat-input-placeholder.mat-empty::before {
content: "My custom placeholder";
color: black;
}
並且如果可以使用CSS變量,則可以從標記中傳遞占位符值:
HTML:
<mat-input-container custom-placeholder="true" style="--custom-placeholder-text: 'Type terms…';">
<input type="text" matInput name="searchText" placeholder="Query">
</mat-input-container>
SCSS:
:host /deep/ :not(.mat-focused)[custom-placeholder] {
.mat-input-placeholder.mat-empty {
color: transparent;
&::before {
content: var(--custom-placeholder-text);
color: black;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.