Ways to dynamically apply styles to the component tag depending on the visibility of its content

Consider a scenario where you have a component with logic to toggle the visibility of its contents:

@Component({
  selector: 'hello',
  template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`,
  styles: [`h1 { font-family: Lato; } div { border: 1px solid blue }`]
})
export class HelloComponent  {
  @Input() name: string;
  visible: boolean;

  ngOnInit() {
    this.visible = this.name === "Stranger"
  }
}

Now, using this component in another component like so:

<div class="container">
  <hello class='hello-class' name="Stranger"></hello>
  
  <!-- This will not be visible -->
  <hello class='hello-class' name="Not stranger"></hello>
</div>

The second use of the hello component remains invisible due to the conditions set inside the component. However, the styles applied to hello-class are still affecting the component even when it's hidden.

You cannot move the logic to directly show/hide the component to the parent element. Therefore, adding an *ngIf before the component is not an option.

Is there a way to apply these styles only if the component is visible?

Check out this stackblitz link for a demonstration of the issue: https://stackblitz.com/edit/angular-ivy-mfrb7j

Answer №1

One way to achieve this without involving children is by utilizing a css selector:

.hello-class:not(:empty) {
  display: block;
  margin-bottom: 80px;
}

When using :not(:empty), it specifically checks if the element (acting as the host for the component) has any children present. If there are no children, then the specified style will not be applied.

https://developer.mozilla.org/en-US/docs/Web/CSS/:empty

Answer №2

Implementing conditional styling using ngClass is another viable option.

To achieve this in your HTML, you would do the following:

<div class="container">
  <hello [ngClass]="{'hello-class': visible}" name="Stranger"></hello>

  <!-- This content will not be displayed -->
  <hello [ngClass]="{'hello-class': visible}" name="Not stranger"></hello>
</div>

When the 'visible' variable is set to true, the 'hello-class' styling will be applied.


Below is an elaboration of the above answer

Approach 1:

Custom Property Binding & ngClass

In hello.component.ts file, make the "visible" property bindable from the parent component:

@Component({
  selector: 'hello',
  template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`,
  styles: [`h1 { font-family: Lato; } div { border: 1px solid blue }`]
})
export class HelloComponent  {
  @Input() name: string;
  @Input() visible: boolean;
  ngOnInit() {
    this.visible = this.name === "Stranger"
  }
}

In parent.component.html, connect to the "visible" property of the hello component and utilize ngClass for conditional styling:

<div class="container">
  <hello [visible]="visibility" [ngClass]="{'hello-class': visibility}" name="Stranger"></hello>

  <!-- This content will not be displayed -->
  <hello [visible]="visibility" [ngClass]="{'hello-class': visibility}" name="Not stranger"></hello>
</div>

In parent.component.ts, include the local property "visibility":

visibility: boolean;

Approach 2

Local Reference & ngClass

Alternatively, if modifying the parent.component.ts file is not an option, you can handle everything in the HTML. There's no need to use the @Input() decorator in your hello.component.ts file for this method. It might seem a bit cumbersome, but it gets the job done.

In parent.component.html, utilize local references to trigger the conditions for ngClass:

    <div class="container">
  <hello #a [ngClass]="{'hello-class': a.visible}" name="Stranger"></hello>

  <hello #b [ngClass]="{'hello-class': b.visible}" name="Not stranger"></hello>
</div>

Answer №3

Assign the name inputs to variables within the component.

public helloNames = [ 'Stranger', 'Not stranger'];

Next, utilize the following code in the component:

<div class="container">
  <hello class='hello-class' *ngIf="helloNames[0] == 'Stranger'" name="{{helloNames[0]}}"></hello>

  <!-- This section will not be visible -->
  <hello class='hello-class' *ngIf="helloNames[1] == 'Stranger'" name="{{helloNames[1]}}"></hello>
</div>

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

Trouble with Ajax requests firing on document load in Firefox

When loading a JSP page in Firefox, I am invoking an AJAX function that calls a servlet. The servlet returns data in response. However, when I attempt to alert the data as shown in the code snippet below, I receive a null value. $.ajax({ url : 'S ...

Trouble with executing asynchronous AJAX request using when() and then() functions

Here is the code that I am currently using: function accessControl(userId) { return $.ajax({ url: "userwidgets", type: "get", dataType: 'json', data: { userid: userId } }); }; var user ...

Tips for including descriptions on individual images within the jQuery PhotoStack gallery

Recently, I encountered a challenge. I am currently utilizing a PHP file for accessing images stored in a specific folder. Here is the snippet of my PHP code: <?php $location = 'albums'; $album_name = $_GET['album_name']; $files ...

I'm struggling with a namespace conflict in Javascript - how can I access this value in the function call?

Having a bit of trouble figuring out how to obtain the desired value within this function. Any ideas? Thanks! temp = exotics[i].split(','); if ($.inArray(temp[0], tblProbables) != -1) { item = $("<li><a id='" + temp[0] + "&apo ...

Utilizing JSONP callbacks in Dart

I've been struggling with implementing basic JSONP in Dart and I can't seem to figure it out. After reading this specific blog post along with another helpful resource, it suggests using window.on.message.add(dataReceived); to receive a MessageEv ...

Do we need to employ strict mode when utilizing specific ES6 functions in Node.js?

There has been a debate circulating at my workplace regarding whether or not it is necessary to include 'use strict' when using ES6 in Node.js without Babel. Some argue that certain ES6 methods may not function correctly without it, but I haven&a ...

What is the best way to interact with Redis without using any external modules?

I am curious about the communication process between the node redis wrapper and the RESP (REdis Serialization Protocol) database. Here is a simple example: const redis = function(uri) { this.client = '' // How do we establish a connection wit ...

Inserting a new key-value pair into each object within an array

I have a collection of items that I need to add a specific key to in AngularJS using $scope. The following code shows the initial objects: $scope.Items = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sw ...

Tips for integrating Server-Side Rendering into an already established React.js app running on Express.js

I am currently working on a React application and I am looking to add SSR using Express.js. Initially, I made a mistake by creating a repository with just a frontend folder containing the entire React app with typescript, babel, and webpack configurations ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

Can you use an ajax post to search for a boolean in MongoDB without converting on the server side?

I am facing an issue with my mongo collection that has documents containing a boolean field: { name : "Tom", active : true } { name : "Jerry", active : false } In my application's client side, there is an element that triggers an AJAX po ...

Obtain an Array Containing all Current Page Paths in Gatsby

While creating a custom `404` page in Gatsby, I am looking to provide users with recommended similar path names based on the non-existent path they have accessed. Can anyone guide me on how to retrieve an array of all the current pages on my website? ...

Respond to a recommendation with a response

I've been working on setting up a bot for my Discord server, and I recently added a "marry" command to it. Whenever a user makes an offer, a message announcing the proposal pops up with two reaction options. The first reaction signifies yes, while th ...

Send an array of data from the view to the Controller in CodeIgniter

I have been searching for a solution to this question. However, for some reason, my code is not functioning properly. Here is what I want to achieve: Data Array -> ajax post -> codeigniter controller(save data in DB and redirect to another page) ...

Retrieve the Nth class of an element that has multiple classes without relying on the .attr("class") method in jQuery

Within a container with two styles, the initial nested div <div class="datacheck"> <div class="classic_div_data customdataid_305"> some values are included here </div> <div class="optiondiv"> </div> </div& ...

What is the best way to improve the design of this division that includes buttons?

I'm having trouble with the layout of three divs I have set up. One acts as a container, while the other two are meant to hold buttons. However, something seems off and I can't figure out how to correct it. .button { display: inline-block; ...

Retrieve the rowid from the first column of a jqGrid row

I want the first column of my jqGrid to display the rowid number number | name | class 1 | A | acceptable 2 | B | good 3 | C | bad Alternatively, I would like to add a column like this (image) https://docs.google.com/file/d/0Bxi6bFcYZ_MgYTI1dUJCMWEtd0E/ ...

Unraveling the mysteries of an undefined entity

When the variable response is undefined, attempting to retrieve its property status will result in an error: Error: Unable to access property 'status' of undefined const { response, response: { status }, request, config, } = error as A ...

Convert this text into HTML code: "Textarea to

I have a basic <textarea> element that I want to transform links (www.google.com, msn.com, etc) and line breaks (\r\n) into HTML code. I found one library for converting links into <a hrefs>. Another library can convert line breaks i ...

What's stopping the error exception from showing up on the client side?

Here's the scenario: I have an action method called SavePoint that contains some logic and throws a System.ArgumentException with the message "Error, no point found". Additionally, there is an ajax function named saveFeature which makes a GET request ...