[英]ngClass: Check if input has value with angular
我有一個帶有浮動label
的input
的angular
component
。 我切換了一個boolean
變量,以在input
包裝器上設置class
,以使label
的浮動animation
在input
元素label
具有angular
(blur)
和(focus)
。 現在,這很好用,當我單擊input
, label
向上設置動畫,而當我離開input
它會將動畫向下設置。 我唯一的問題是,當我在input
鍵入一個值並將其保留時, label
應保持浮動在input
上方。 此刻,它向下動畫並覆蓋該value
。 例如,如果isFocused
為true
或 label
具有value
,如何在ngClass
檢測class
?
這是我的代碼。 在stackoverflow片段中,僅支持angularjs
,因此我無法在此處創建片段,對此表示angularjs
!
HTML:
<div class="my-input" [ngClass]="isFocused ? 'state-my-input--active' : ''">
<div class="my-input__wrapper">
<label class="my-input__label">Label</label>
<input type="text" class="my-input__input" (blur)="isFocused = false" (focus)="isFocused = true">
</div>
</div>
SCSS:
.my-input {
display: flex;
flex-direction: column;
margin-top: 50px;
}
.my-input__wrapper {
display: flex;
flex-direction: column;
position: relative;
}
.my-input__label {
bottom: 8px;
color: blue;
font-size: 14px;
position: absolute;
transition: all 0.3s ease-in-out;
}
.my-input__input {
border: none;
border-bottom: 2px solid darkgray;
color: blue;
transition: border-color 180ms linear;
}
.state-my-input--active {
.my-input__wrapper {
.my-input__label {
transform: translateY(-15px);
cursor: default;
}
.my-input__input {
border-bottom-color: blue;
}
}
}
JS:
import { Component, OnInit } from "@angular/core";
@Component({
selector: "my-input",
templateUrl: "./my-input.component.html",
styleUrls: ["./my-input.component.scss"]
})
export class MyInputComponent implements OnInit {
isFocused: boolean = false;
constructor() {}
ngOnInit() {}
}
嘗試:
[ngClass]="{'state-my-input--active': isFocused}"
要獲得條件下的值,只需使用(當然,您必須先定義並綁定值:
[ngClass]="{'state-my-input--active': isFocused || value != ''}"
要么
[class.state-my-input--active]="isFocused || value != ''"
首先在您的輸入中定義[(ngModel)]
。 然后嘗試使用這種方法添加類。
<div class="my-input" [ngClass]="{'state-my-input--active': isFocused || someValue}">
<div class="my-input__wrapper">
<label class="my-input__label">Label</label>
<input type="text" class="my-input__input" [(ngModel)]="someValue" (blur)="isFocused = false" (focus)="isFocused = true">
</div>
</div>
或者,您也可以將角形材料用於浮動標簽。要查看示例,請點擊此處
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.