Enhance your Angular app by dynamically adding classes to existing classes on a host component

How can I dynamically add a class to the host component of this angular component?

@Component({
 selector: 'test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss'],
 encapsulation: ViewEncapsulation.None
})

export class TestComponent implements OnInit {

  @HostBinding('className') componentClass: string;

  @Input() name: string;

  constructor() {}

  ngOnInit(): void {
   this.componentClass = this.name ? `test-icons test-icons-${this.name}` : '';
  }

}    

The current setup overrides any additional classes I try to add. For example, if I include:

 <test-component class="custom-class-i-added" [name]="'icon']></test-component>

The "custom-class-i-added" disappears. Is there a way to dynamically add classes without overriding the existing ones?

Answer №1

Here's the solution you've been looking for:

export class HelloComponent implements OnInit  {
  @Input() name: string;
  
  // Utilizing input to merge the class passed from parent with classes defined in component.
  @HostBinding('class') @Input('class') classList: string = '';

  ngOnInit() {
    this.classList = `${this.classList} test-icons test-icons-${this.name}`;
  }
}

Answer №2

One method to address this issue is by utilizing the @Attribute decorator in order to access the component's class attribute and then concatenate it with componentClass as shown below:

component.ts

constructor(@Attribute('class') private hostClass: string){}

  ngOnInit(): void {
   this.componentClass = this.name ? `${this.hostClass} test-icons test-icons-${this.name}` : this.hostClass;
  }

See a Demo Here

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

Issue with file uploading in Angular 9 as the uploaded file is not being added to the

I've set up a form group in the HTML of my Angular 9 app that includes an upload feature for files. The file upload works fine when calling the handleFileInput function, as I can confirm from the console log output. However, even though the file gets ...

When uploading from Angular 2, PHP fails to populate the $_POST and $_FILES variables

I'm encountering difficulties when trying to upload files and data to my server using Angular 2 and PHP. After following the instructions in File Upload In Angular 2? to upload data and files from Angular 2, everything appears to be functioning corre ...

Angular Image Cropping: A How-To Guide

I have been on the lookout for an Angular plugin that allows me to crop images before uploading them to the database. Despite spending all day searching, I have not been able to find a suitable plugin that meets my requirements. What I need specifically i ...

The latest version of Angular, Angular 16, brings along its own set of challenges

Just completed the update to version 16 of Angular and encountered the following error message: The injectable CustomMsalInterceptor inherits its constructor from MsalInterceptor, but MsalInterceptor does not have its own Angular decorator. This will resu ...

Experiencing an array of issues while attempting to convert my HTTP request into an

I am currently facing some difficulties in converting my HTTP requests into observables. Within my Angular App, there is a service called API Service which takes care of handling all the requests to the backend. Then, for each component, I have a separate ...

Develop a versatile factory using Typescript

For my current project, I am developing a small model system. I want to allow users of the library to define their own model for the API. When querying the server, the API should return instances of the user's model. // Library Code interface Instanc ...

Here is a guide on sorting through data within an array of objects using React.js and Typescript

How can I filter dealers' data based on the minimum and maximum price range of a slider change? I am retrieving dealers' data using an API and storing the slider's min and max values in a handle change function. What is the best way to filte ...

An error with code -4058 is preventing the installation of npm packages when running the 'npm install' command after using 'ng new'

Embarking on a new Angular project, I encountered an issue while trying to install packages listed in my package.json file. Despite multiple attempts on both of my computers, the same error persisted, leaving me baffled. Determined not to give up, I seek g ...

Using Handlebars.js with Angular CLI versions 6 and above: A Step-by-Step Guide

Looking to create a customizable customer letter in either plain text or HTML format that can be edited further by the customer. Considering using Handlebars.js to render an HTML template with mustache tags, using a JSON object for business information. T ...

When performing an arithmetic operation, the right operand must be a data type of 'any', 'number', 'bigint', or an enumeration type

My JavaScript code needs to be converted to TypeScript for proper functionality. categoryAxis.renderer.labels.template.adapter.add("dy", function(dy, target) { if (target.dataItem && target.dataItem.index % 2 === 0) { return dy + 25; } ...

Angular application triggering multiple subscribe method calls upon a link click event

Here is the code for my navbar component: <li *ngFor="let item of menu"> <a *ngSwitchCase="'link'" routerLinkActive="active" [routerLink]="item.routerLink" (click)="Navigation(item.title)&q ...

When executing prisma generate, an error of TypeError is thrown stating that the collection is

While using typescript with Prisma, I encountered an issue when trying to run prisma generate, as it kept throwing the following error: TypeError: collection is not iterable. at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21) at ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error. ...

Angular 6 triggers NavigationCancel event when encountering valid guards

I'm encountering difficulties with the Angular router while trying to navigate to a specific state. Despite my attempts to utilize a custom guard with canLoad() and canActivate() functions that return true, I have not been successful. The Angular do ...

How can I configure Angular to redirect to an error page whenever an error is encountered in an HTTP API request?

With over 50 HTTP APIs in my application, I'm looking for a way to automatically route to a specific page whenever an error message or issue arises with one of the APIs. Instead of manually adding routing to each service, I want to find a simpler and ...

Running Angular/Rxjs store (ngrx) calls synchronously

After fetching 2 items from my store using ngrx, I need both requests to complete before taking further action. Here's an example of what I'm trying to achieve: const item1$: Observable<Item> = this._store$.select( ItemStoreSelectors.sele ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

How can you merge arrays in Angular based on their unique names?

Is there a way to combine objects within the same array in Angular based on their names? [{ "name":"Navin", "id":"1" }, { "name":"Navin", "mark1":"98" ...

Tips for Fixing Error: "We received a visitor for node type TSSatisfiesExpression that is not recognized as a valid type."

There seems to be an issue with Babel unable to compile my Storybook code. I'm working on setting up a boilerplate with Storybook and Next.js I've searched for a solution to this problem but couldn't find one. Any help would be greatly app ...

I am looking to customize the mask input in my angular 7 application so that it allows either a "-" or a digit as the first character, with all subsequent characters being digits. How can I make this modification?

Within my Angular 7 application, I am working on a method that masks user input. Currently, the method restricts users from inputting anything other than digits. However, I need to modify it so that users can input either a "-" or a digit as the first char ...