Validate input content using Angular's ngClass directive

In my Angular project, I have created a component for an input field with a floating label. The label animates up when the input is focused and animates back down when it loses focus. However, I am facing an issue where if a value is typed in the input field and then left, the label overlaps the value instead of staying floated above the input. How can I modify the ngClass to keep the label floated when the input is not empty or focused?

Unfortunately, I cannot provide a snippet here as only AngularJS is supported on this platform. Here is the code:

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() {}
}

Answer №1

Experiment with:

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

Answer №2

To begin, set up [(ngModel)] on your input element. Then, implement the following method to add a class.

<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>

Alternatively, you can utilize Angular Material for floating labels. For examples, visit this link.

Answer №3

If you want to obtain the value in your condition, remember to define and bind the value first:

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

Alternatively, you can use:

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

For more information, refer to https://angular.io/api/common/NgClass

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding Floating Point Numbers in TypeScript Objects

Recently, I've been encountering some strange results while trying to sum up my floating point values. The output seems off with 8 decimal places and other unexpected outcomes. All I really want to do is add up the protein values of various objects to ...

What is the best way to integrate LESS css into a Reactjs application?

I am looking to incorporate LESS into my React app, but I have been unsuccessful in finding a solution through Google. As a newcomer to ReactJs, I lack deep knowledge and would greatly appreciate guidance on installing Less. If anyone is able to help me ...

Having trouble creating an angularjs table using ng-repeat in the controller?

I have a sample snippet that I would like to discuss. My goal is to display a JSON object in an angular table using ng-repeat, which is being generated from my angular controller script. I have attempted the code below, but for some reason, the table is no ...

Activate a dropdown menu following the selection of a date on a calendar input using vue.js

What I need to do is have two select fields, one for 'days' and the other for 'hours'. When a day is selected, the user should then be able to choose between two available time slots. If they choose day two, the available time slots sh ...

Troubleshooting: Issue with Updating Views in Angular JS

I've been attempting to change the view from the controller, but it's just not working properly. app.js var app = angular.module('vla', ['ngRoute']); app.config(function ($routeProvider){ $routeProvider ...

Strategies for integrating data from a modal .ts file into another file

Unsure if 'inject' is the correct term. I am relatively new to coding, and while my dad is helping me out, I wanted to give StackOverflow a try with my question. Apologies in advance if it's hard to understand. Context: I am creating a tab ...

I'm facing an issue where the data I retrieved is not displaying properly in my template within nuxt 3

After fetching data from an api, I can see it logged in my async function. However, the data stored in my array is not rendering on my template in Nuxt 3 The script setup includes: //ARRAY OF ALL THE DAILY WEATHER DATA PER DAY let allDataWeather=[]; ( ...

the three.js code runs smoothly on JSfiddle, but it does not seem to be working properly

Check out this basic three.js code snippet for generating custom geometry http://jsfiddle.net/67Lgzjpb/. After attempting to run this code directly in my browser (not via JSFiddle), an error message pops up: TypeError: geom.computeCentroids is not a funct ...

Updating model values while dragging with Angular Dragular

Currently, I am experimenting with dragula and its newer version, dragular, on some sample projects. One specific dilemma I am facing involves the implementation of drag and drop functionality in an Angular project. My query pertains to utilizing a list o ...

Issue encountered with SQL server 2008 due to connection error

My current struggle lies in the connection I am attempting to establish with SQL Server. Unfortunately, whenever I try pressing the period key or entering the server name, I encounter difficulty connecting to SQL Server. ...

What is the process of passing a JavaScript variable to PHP with AJAX?

In the given scenario, I have an HTML file that is intended to display the content of a text file at div id="myDiv". The text file content will be read by PHP. However, there seems to be an issue in retrieving the content from the text file. I need assis ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

Is there a way to use jQuery to assign a value to an input element based on its "name" attribute alone?

Is it possible to reset certain text-boxes that have a unique name, but not a unique id? I attempted using jQuery for this task, however, the following code does not seem to be effective: $('input[name=customergroupname]').value=""; ...

Columns are not properly aligning side by side within the .card class

I am facing an issue where my cards are not lining up inline next to each other in columns but are instead jumping under each other. I have tried setting the col-md-6 class to align two of them next to each other, but that did not work. I have also checked ...

initiating a form submission with an anchor tag

I currently have a form with three buttons: cancel, save (submit), and save continue. The JavaScript is called via a function from the form's onsubmit method, and everything works as expected except for the save and continue button. Here is a simplifi ...

There was an issue found at line 18 in the backend.service.d.ts file of the node_modules/angular-in-memory-web-api, showing error TS1086 which states that an accessor cannot be declared

I encountered this issue right after installing 'angular-in-memory-web-api'. import { InMemoryDbService } from "angular-in-memory-web-api"; and subsequently, the following error messages appeared: ERROR in node_modules/angular-in-memory-we ...

Oversee various interactions for the user

I am currently utilizing NodeJs, ExpressJs, and Angular 6 for my application, but I have encountered an issue. Within my system, there is a user with the attributes: User U: { name; email; password; } Let's assume this user, named U, is ...

What are the steps to sorting in JavaScript?

I need help with sorting an array. The array I have looks like this: var temp = [{"rank":3,"name":"Xan"},{"rank":1,"name":"Man"},{"rank":2,"name":"Han"}] I've tried to sort it using the following code: temp.sort(function(a){ a.rank}) But unfortun ...

The column-count attribute in CSS3 allows for the creation of

I have a short CSS code snippet that sets the styles for a specific div. It includes properties such as border style, margin, background color, text color, padding, alignment, and column layout. div#mydiv{ border-style: none; margin-bottom: 1em; b ...

Is there a way for me to retrieve a single object from an array using checkboxes?

I am facing an issue with my function that is supposed to console.log the selected object from a checkbox. However, when I select only one checkbox, it logs everything instead of returning just the value from the checkbox. Here is the relevant HTML code: ...