ngClass: проверить, имеет ли значение ввода значение angular - PullRequest
0 голосов
/ 03 декабря 2018

У меня есть angular component для input с плавающей label.Я переключаю переменную boolean для установки class в оболочке input, чтобы сделать плавающее animation для label с angular (blur) и (focus) для элемента input.Теперь это работает нормально, когда я нажимаю input, анимация label поднимается вверх, а когда я покидаю input, анимация возвращается вниз.Моя единственная проблема заключается в том, что когда я набираю значение в input и оставляю его, label должен оставаться выше input.На данный момент он оживляет и перекрывает value.Как я могу определить, например, в моем ngClass, если isFocused равен true или , label имеет value, чтобы сохранить class?

Вот мой кодВ фрагменте stackoverflow поддерживается только 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() {}
}

Ответы [ 3 ]

0 голосов
/ 03 декабря 2018

Чтобы также получить значение в вашем состоянии, просто используйте (конечно, вы должны сначала определить и связать значение:

[ngClass]="{'state-my-input--active': isFocused || value != ''}"

или

[class.state-my-input--active]="isFocused || value != ''"

см. https://angular.io/api/common/NgClass

0 голосов
/ 03 декабря 2018

сначала определите [(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>

или вы можете использовать угловой материал для плавающих надписей. Чтобы увидеть примеры, нажмите здесь

0 голосов
/ 03 декабря 2018

Попробуйте:

[ngClass]="{'state-my-input--active': isFocused}"
...