Applying classes dynamically to a custom form component in Angular to tailor its appearance

I am currently working on a custom form component where I need to dynamically apply classes to it.

import { Component, forwardRef, Injector } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { BaseInput } from './base-input';

@Component({
  selector: 'app-text-control',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => TextControlComponent),
    multi: true
  }],
  styles: [':host { display: inline-block }'],
  template: `
    <ng-container *ngIf="ctx.isEditing">
    <input class="form-control"
    [value]="value"
    (change)="value=$event.target.value" (keyup)="value=$event.target.value" >
    </ng-container>
    <ng-container *ngIf="!ctx.isEditing">
    {{value}}
    </ng-container>
  `
})
export class TextControlComponent extends BaseInput<string> implements ControlValueAccessor {
  constructor(injector: Injector) {
    super(injector);
  }
}

The challenge arises when applying bootstrap classes to the component in the HTML as the container receives the classes instead of the child HTML element.

 <app-text-control formControlName="test" [ngClass]="{
        'is-valid' : test.valid && (test.dirty || test.touched)  ,
        'is-invalid' : test.invalid && (test.dirty || test.touched)  
      }" ></app-text-control>

The situation is such that the class is-valid or is-invalid gets applied to the app-text-control container HTML rather than the inner input control. Is there a way to propagate the ng-class classes set in the parent to the child HTML?

I aim to be able to dynamically assign classes to the HTML within my custom component, preferably utilizing the ngClass directive if feasible. Does this require creating a custom attribute (e.g., [myNgClass]=....) for it to function correctly within my parent custom form control?

Answer №1

Perhaps there's a different approach to consider, but one way to potentially tackle this is as follows:

<app-text-control formControlName="test" [isvalid]="test.valid && (test.dirty || test.touched)" [isinvalid]="test.invalid && (test.dirty || test.touched)" ></app-text-control>

Within the child component, you can utilize the isvalid and isinvalid properties in conjunction with 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

How do EventEmitter<undefined> and EventEmitter<void> differ from each other?

At times, there may be a situation where we need to omit the generic variable. For example: @Component( ... ) class MyComponent { @Output() public cancel = new EventEmitter<undefined>(); private myFoo() { this.cancel.emit(); // no value ...

The sticky-top class in Bootstrap 4 does not seem to be functioning properly on the

It seems that other classes in my codebase are interfering with the sticky-top class from Bootstrap. I initially thought that all I had to do was add the class to the navbar, but with two navbars and restrictions on using fixed-top, things have become tric ...

Difficulties encountered while attempting to modify a class using Javascript

Recently, I've encountered an issue with my JavaScript where I am unable to keep a particular element's class changed. Despite attempting to change the class to "overlist", it only stays that way briefly before switching back to its original stat ...

Having trouble achieving the expected result in the form array using Angular response

An exam platform was developed where administrators could create quizzes. However, when attempting to edit a quiz, not all questions and options were displayed in the form array from the response. Surprisingly, editing and accessing array data locally work ...

Playground Themed Central Menu Features

Check out the theme live preview here: I've been experimenting with different combinations of text-align: center; and margin: 0 auto; but I'm struggling to align the menu elements to the center of the page. Any assistance would be highly apprec ...

The speed at which Angular is hiding elements is too rapid for any animation to keep up with

Utilizing Angular 1.2 in conjunction with the animate.css library available at The animations I'm implementing are geared towards simple ng-show="somevalue". The ng-show animations are functioning properly, smoothly fading in. However, when the eleme ...

Required Peer Dependency Not Satisfied: [email protected] is requesting @angular/[email protected]

DETECTED Missing Dependency: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5525393421333a27387837273a2226302778312c3b34383c3615617b667b60">[email protected]</a> requires @angular/<a href="/cdn-cgi/l/email-prot ...

Creating a grid of CSS/JavaScript circles

Trying to achieve something like this: It sounds simple, but there are specific requirements: - the width of the parent div should adjust according to the length of the text (is this feasible with CSS?) - random positioning of all circles is proving to be ...

Angular - choose an input field and then tap on a different button to increase the value

Currently, I am working on adding a functionality to my material table that consists of several input fields. My goal is to create a function where selecting an input field will allow me to increment its value using a separate '+' button. The is ...

Ways to create gaps between rows of a table

I have been attempting to replicate the layout of this table: https://i.sstatic.net/1QuFD.png However, I am running into an issue with the spacing between the rows (border-spacing: 0 2px), and I'm not sure why. Can anyone provide any guidance on thi ...

Refactoring TypeScript components in Angular

How can I streamline the TypeScript in this component to avoid repeating code for each coverage line? This angular component utilizes an ngFor in the HTML template, displaying a different "GroupsView" based on the context. <div *ngFor="let benefitG ...

Adjust the color of the icon depending on the value

I am new to Angular2 and I'm looking for a way to dynamically change the CSS of an icon based on specific values. Here is the code in HTML: <li><i class="fa fa-check" [style.color]="'switch(types)'"></i>{{ types }}</l ...

Issue with Angular: Attempting to assign a value to a property that is undefined within

While utilizing a common method to call a service that executes two functions upon success and failure, I encountered an issue. Despite the call executing correctly, I faced an error when trying to assign a value from the service result to a variable withi ...

The pseudo-class for invalid input triggers CSS invalidation, even when the input field is left blank

The input property for handling invalid input is currently malfunctioning. It triggers an error even when the input field is left empty. I would like the input border to be goldenrod when it's empty, turn red if the input doesn't match the specif ...

Graph is vanishing while linked

A unique HTML canvas is included in a standalone file called dashboard.html. To display the dashboard on the main homepage (home.html), we utilize ng-view nested within an ng-if directive. Oddly, clicking on the hyperlink "#" from the home page causes th ...

What is the best way to conceal a dropdown menu when the page first loads?

I have a dropdown menu that is displaying like this: <ul> <li class="dropdown open"> <a aria-expanded="true" href="#" class="dropdown-toggle waves-effect waves-button waves-classic" data-toggle="dropdown"> <spa ...

Is there a way to adjust the zoom levels of specific sections on my website when using Ctrl-+ and Ctrl--?

It's interesting how I have split elements of my Dreamweaver web page between the <body> section and the <div class="twoColFixRtHdr"> Dreamweaver template nested within it. This setup causes the two areas to zoom in at different rates when ...

Arrange elements within a division when the division splits into two rows

Currently in my setup: I have a navigation bar with a group of buttons located on the right-hand side. When the navbar is reduced to a smaller size, like on a smartphone, the two buttons get split across 2 rows within the div. In this state, I'm ai ...

Angularfire2 retrieve list of data with a specified number of items from the

I am facing a challenge in retrieving a specific node from my firebase database. https://i.sstatic.net/YDevB.png The technologies I am using include: "angularfire2": "^5.0.0-rc.4", "firebase": "^4.9.0", In my component code, you can find the following ...

Ensure that a child container automatically adjusts its width to fit within a parent container of varying width

There is a wrapping container that contains three floated containers inside. The width of the wrapping container is variable. The inner container on the left has a width of 100px, and the inner container on the right has a width of 500px. The center contai ...