Implementing dynamic class changes with *ngIf within a child component

Apologies if this question has been addressed before, I found two similar answers here:

Question related | Close Solution

An Angular Material Sidenav component contains three components. The parent component (highlighted in red) includes tab-like buttons that load one of the three components upon clicking.

<button (click)="onTabClick(1)"><i class="fas fa-layer-plus"></i>
<button (click)="onTabClick(2)"><i class="fas fa-map-marker-edit"></i></button>
<button (click)="onTabClick(3)"><i class="fas fa-plus-square"></i></button>

The buttons switch out components using *ngIf

 <app-map-features *ngIf="tabIndex === 1" [id]="'test'" ></app-map-features>
 <app-map-edit-live-data *ngIf="tabIndex === 2" [id]="'test2'" ></app-map-edit-live-data>
 <app-map-zoom *ngIf="tabIndex === 3" [className]="'other'"></app-map-zoom>

TypeScript:

export class containingComponent implements OnInit {
  tabIndex = 1 ;    
  onTabClick(index) {
    this.tabIndex = index;
  }

A background color is applied to the Font-Awesome icon on click, working as intended.

.fas:hover {
  background-color: $primary-color;
}

The objective is to change the .fas background color when a specific component is displayed, indicating which component's content is visible.

I won't delve into unsuccessful attempts, but how can I update the class to reflect the tabIndex value and make components aware of each other?

https://i.sstatic.net/gwved.png

Answer №1

From what I gather, you're looking to change the background color depending on the selected component. You can achieve this by using [ngClass] and dynamically switching classes based on the tab index as shown below:

HTML:

<red-outline-component 
  [ngClass] = "{'map-features-bg': tabIndex === 1, 'map-edit-bg': tabIndex === 2, 'map-zoom-bg': tabIndex === 3}">
    ...
</red-outline-component>

CSS: (You don't have to specify the color in each class, but it helps customize the text color for better readability).

.map-features-bg {
  background-color: some-color;
  color: some-color;
}

.map-edit-bg {
  background-color: some-color;
  color: some-color;
}

.map-zoom-bg {
  background-color: some-color;
  color: some-color;
}

The use of [ngClass] allows for dynamic application of classes based on variable values. For more information, refer to the documentation here.

I hope this explanation is helpful!

Answer №2

Just a heads up, there seems to be a missing ending tag on the first button - unless it's intentional

<button (click)="onTabClick(1)"><i class="fas fa-layer-plus"></i> {insert content}

Answer №3

Qarun made a valid point in both scenarios. I found that ngClass was more effective than ngStyle because I am using SCSS and the color is actually a variable. What surprised me was discovering that I could incorporate logic into ngClass just like with ngIf.

<button (click)="onTabClick(1)"><i class="fas fa-layer-plus"
                                             [ngClass]="{'darkBackgroundClass': tabIndex === 1}"></i></button>

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

Incorporate a website design template into your Visual Studio project

I have a website application that I created but it's currently empty. I would like to add some style to it using online free website templates that I downloaded. However, I'm unsure of how to incorporate the css, font, and images folders into the ...

Is it possible that VS Code can't recognize 'ngbNavItem' as a valid property of 'li'?

The current situation: Our Angular app is in production and utilizes various libraries such as ng-select, angular-fontawesome, ng2-charts, ngx-quill, ng-bootstrap, and others. Everything seems normal with these libraries except for ng-bootstrap, which alo ...

IE8 - Unable to use rgba()

I'm currently facing an issue with RGBA() manipulation in jQuery while using IE 8. Here's the code I have so far: $('.set').click(function (e) { var hiddenSection = $('div.hidden'); hiddenSection.fadeIn() . ...

The issue with the Hidden Content feature in the Slick Carousel is that it does not function correctly on the

There are some related topics worth exploring, such as: Slick carousel center class not working when going from last item to first item Despite trying various solutions, the issue still persists in my code. My goal is to have each item displayed in the ce ...

Triggering JavaScript Function When Scrolling in Overflowed DIV

After using jQuery and searching for various ways to make this script work, I finally found a solution that works for my index.html file. <div style="overflow-y:scroll; height:300px"> <div style="background-color:black; height:500px"> </div ...

Issue with PHP retrieving initial value of post data

Hi there, I am facing an issue with my PHP code where the first value of the input field is not being displayed. However, when I check the console.log, it shows correctly. Here is my console.log output: https://i.sstatic.net/eZvg6.png PHP Output: https ...

Utilizing a variable to pass props to a component (instead of a static component) within React Router 5

In react-router 5, you can pass props to a child component in this way: <Route path="/" exact render={ props => <MyPage title={myTitle} dataPath={myDataPath} {...props} />} /> However, I am using a route model in my ...

AngularJS: The dynamic setting for the stylesheet link tag initiates the request prematurely

I'm encountering a problem that is somewhat similar (although not exactly the same, so please be patient) to the one discussed in Conditionally-rendering css in html head I am dynamically loading a stylesheet using a scope variable defined at the sta ...

Discrepancy in Syntax Highlighting in HAML Code

Hopefully this is an easy fix, as I am struggling with highlighting some HAML code using the prism library. %pre %code.language-haml &#37;header.post-header &#37;h1= data.title &#37;time{ datetime: data.date }= pretty_date(data.d ...

The parameter type 'void' cannot be assigned to the parameter type 'SetStateAction<{}>'

Currently, I am in the process of developing an application utilizing TMDB with NextJS and Typescript. Within my movies.ts file, I have implemented the following code: export async function getTrendMovies() { const url = 'https://api.themoviedb.o ...

Safeguard your HTML, PHP, and image files from being monitored

What methods can be used to safeguard your files, such as PHP and image files, from being tracked by tools like TeleportPRO and HTTrack? Your time is greatly appreciated. Thank you! ...

Can a list be transformed into a toolbar in a responsive design?

Here is my card with a nav section that includes multiple items (although I've only included one here for simplicity). <div class="col-md-3"> <div class="card"> <div class="card-header"> ...

What is the best way to deactivate the onclick event after it has been triggered?

There was an image that triggered the add_cart() JavaScript function when clicked using onclick() <img src="images/add.png" onclick="add_cart()"> The goal is to limit the user to clicking the image only once. Upon the first click, the add_cart func ...

Is it possible for a lambda in TypeScript to have access to the class scope but return undefined

In my TypeScript code, I have a class used as a Pipe in Angular 2 to render markdown. It compiles successfully but encounters a runtime exception on a specific line: var Remarkable = require('remarkable'); @Pipe({ name: 'markdown' ...

Adding a CSS class to a LinkButton upon clicking in an ASP.NET application

Let's say I have 3 link buttons on a webpage, <asp:LinkButton ID="LB1" runat="server" CssClass="regular" OnClick="LB1_Click"> Today </asp:LinkButton> <asp:LinkButton ID="LB2" runat="server" CssClass="regular" OnClick="LB2_Click"> ...

There is no data in $_POST when using php5.6

I have exhausted all the solutions on clearing $_POST after submitting a form on Stack Overflow, but none of them resolved my issue. I am currently using Wamp server and PHPStorm. Adjusted post_max_size and upload_max_filesize values in php.ini $_GET is ...

Code update results in a blank screen on Angular-NativeScript application

Currently diving into the world of NativeScript, I encountered a curious issue. Installing one of the sample apps was a breeze, with the emulators functioning perfectly post-installation. However, as soon as I make even the slightest code tweaks and save t ...

Using JavaScript to define an array of objects

My issue lies with transforming a JSON structure like the one below: [{ "groupid": 29, "percentage": 14 }, { "groupid": 29, "percentage": 22 }, { "groupid": 59, "percentage": 66, }] I am looking to convert it into the format shown ...

Steps for executing a single test across multiple URLs using Playwright

My goal is to run a test for over 1000 URLs as quickly as possible. However, I am encountering a timeout error when the number of URLs exceeds 10. It seems like the tests are running sequentially, causing delays. Is there a way to run these tests in parall ...

I'm unsure about the JavaScript toolkit framework's handling of selecting HTML class attributes

I have been exploring the Electron Framework using a JavaScript toolkit known as Xel. In my main.js file, I am working with the following syntax: document.querySelector("menu.selected").className.remove('selected') In my Xel code snippet, I hav ...