Angular styling for input elements that are in the pristine state

Hey there, I'm working with a CSS class that applies a red border to an input field when it is required and invalid, and changes to green when it becomes valid.

CSS

.ng-valid[required], .ng-valid.required  {
  border-left: 5px solid #42A948; /* green */
}

.ng-invalid:not(form)  {
  border-left: 5px solid #a94442; /* red */
}

HTML

<input
              type="text"
              class="form-control"
              placeholder="Vehicle Code"
              [formControl]="codeControl"
              required
            />

Now, I'm looking to change the left border color to something else when the input field hasn't been touched yet. Currently, on page load, the default left border is red and changes to green when validated.

Answer №1

To style elements dynamically in Angular, you can utilize either ngStyle or ngClass.

In the following example, I have opted to use ngClass as my preferred method.

Here is an example of the CSS in the Component.css file:

.valid {
  border-left: 5px solid #42A948;
}

.required {
  border-left: 5px solid #a94442;
}

Within the Component.html file, you can implement the styling like so:

<form [formGroup]="form">
  <input 
    type="text" 
    [formControl]="name" 
    [ngClass]="{'required': name.invalid && (name.dirty || name.touched), 'valid': name.valid && (name.dirty || name.touched)}"
  >
</form>

The Component.ts file contains the necessary logic to handle form validation:

export class AppComponent  {
  constructor() { }

  form = new FormGroup({
    name: new FormControl('', Validators.required)
  });

  get name(): AbstractControl {
    return this.form.get('name')
  } 
}

For your convenience, I have provided a link to a Stackblitz demonstration:

https://stackblitz.com/edit/angular-5xsg7r

Enjoy coding and happy styling! :-)

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

Adjust the menu scrollbar position to the right or limit scrolling to within the menu area

$(function() { "use strict"; $(".navbar-toggler").on("click", function() { $(".navbar-toggler").toggleClass("collapsed"); $(".offcanvas-collapse").toggleClass("open"); let menuposition = $("#toggler").offset().left + $("#toggler").width() + ...

Securing communication between Angular 2 web pages and the ASP.NET Core server through encryption

I'm relatively inexperienced in this field, so I have a simple question. I am familiar with making Angular 2 Http calls and working with ASP.NET Core Authorization and Authentication. However, I'm wondering if there is encryption of data between ...

Utilizing CSS and jQuery to align images in the center of the screen

I'm attempting to display a larger image when hovering over a thumbnail using jQuery and CSS. I have two images like this <td> <% if camera["is_public"] == "t" %> <img src="https://media.evercam.io/v1/cameras/&l ...

How to integrate a toggle switch into an Angular datepicker component

Can the toggle switch be placed inside the calendar? I would like to have it positioned at the top of the open calendar so that users can choose to view date details using the toggle switch <form #uploadForm="ngForm" (keydown.enter)="$event.preventDe ...

Using R Markdown and Hugo to Style Blog Titles

I am currently utilizing Hugo and Blogdown to craft a blog following the guidelines outlined here. The title of my blog is specified at the beginning of each post, resembling the example below: --- title: One Two Three author: First Last date: '2019- ...

Issues with code functionality following subscription via a POST request

I'm currently facing an issue with a service that utilizes an HTTP post request to communicate with the database. Unfortunately, when I try to implement this in my .ts file, nothing seems to happen after subscribing to the post. The post itself works ...

Error: No injection provider found for function(){}!

After countless hours of setting up a custom AOT in Angular 7 project without CLI and debugging, I have encountered the following error: Uncaught Error: StaticInjectorError(Platform: core)[function(){}]: NullInjectorError: No provider for function(){}! ...

Enhance mix-blend mode or filtering effects in SCSS using an SVG component in VueJS

I am currently developing a fixed navbar at the top of a webpage with several SVGs inside anchor tags. I want the SVGs to appear black when displayed over lighter colored divs (other Vue components) and white when displayed over darker colored ones. The ba ...

How can one correctly log out of an Angular application that is integrated with Firebase Authentication and Firestore?

How can I efficiently sign out of an Angular application that uses Firebase Authentication and Firestore? Although I can successfully sign in with Google authentication, signing out poses some challenges. My ultimate goal is to ensure that when a user cli ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

Leveraging the power of JavaScript to reveal concealed div elements

I've got a collection of divs (five in total) with a hidden class applied to them in my CSS stylesheet. Each div also has its own unique ID. My goal is to use JavaScript to reveal these divs one by one. Here's an example of what I'm looking ...

The media query will only impact elements and classes within the index.html file, and will not apply to any other

As I strive to optimize my website for mobile devices, I am encountering an issue with my media queries. The classes don't seem to respond appropriately on any page other than the index.html, and I'm struggling to identify the root cause. Index. ...

implement some level of control within the ngFor directive in Angular

For instance, let's say I have an ngfor loop: <ng-container *ngFor="let setting of settings | trackBy: trackById"> <button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-me ...

Unable to connect input with abstract classes at a hierarchy depth of 2 levels or more

When working on my Angular application: If a Component utilizes an Input that is defined in its immediate parent (abstract) class, everything runs smoothly. However, if a Component uses an Input that is declared in a parent class located two levels a ...

How can I bring the toolbar to the forefront of the page in an Angular/HTML environment?

I am currently facing an issue with bringing the toolbar to the forefront of the page. When I scroll down, the elements on the page end up covering the toolbar which is not the desired behavior. Below is the CSS code for the toolbar: .maintoolbar.mat-tool ...

Alignment of Submenus in a CSS Vertical Menu

I'm currently facing an issue with my vertical menu and submenu alignment. Despite everything working correctly, the submenu does not align horizontally as expected, instead shifting up against the header div above it. Any assistance to resolve this w ...

What could be causing this div to shift positions when the browser window is resized?

When resizing the browser, I'm having trouble keeping the div boxes in place. The bottom-right lower div (vd-grid-sub-box) keeps shifting away when I slightly decrease the browser size. Additionally, vd-grid-right-col overlaps with the banner if the s ...

Looking to build a unique form validator for two inputs? Ensure that one input number is consistently larger than the other with this guide

Is it possible to create a custom form validator with 2 inputs? My goal is to ensure that one input number is always greater than the other. ValidateMaxMin(control: FormControl) { console.log(control.value.productMin); if (control.value.productM ...

Maintaining text color while adding a color overlay to a Bootstrap Jumbotron

After searching extensively, I couldn't find any mention of this particular issue. According to the Bootstrap 4.2 documentation on the Jumbotron, I constructed my div with an inline background image. However, when I attempted to apply an overlay on to ...

Encountering NaN in the DOM while attempting to interpolate values from an array using ngFor

I am working with Angular 2 and TypeScript, but I am encountering NaN in the option tag. In my app.component.ts file: export class AppComponent { rooms = { type: [ 'Study room', 'Hall', 'Sports hall', ...