簡體   English   中英

ngClass:檢查輸入是否具有角度值

[英]ngClass: Check if input has value with angular

我有一個帶有浮動labelinputangular component 我切換了一個boolean變量,以在input包裝器上設置class ,以使label的浮動animationinput元素label具有angular (blur)(focus) 現在,這很好用,當我單擊inputlabel向上設置動畫,而當我離開input它會將動畫向下設置。 我唯一的問題是,當我在input鍵入一個值並將其保留時, label應保持浮動在input上方。 此刻,它向下動畫並覆蓋該value 例如,如果isFocusedtrue 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 != ''"

參見https://angular.io/api/common/NgClass

首先在您的輸入中定義[(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM