Designating a class that applies to every Angular template that can be displayed using *ngIf

I have a specific CLASS called section that I want to apply to a DIV for rendering. Surprisingly, it functions as expected.

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates>
  <div class="section">...</div>
</ng-template>

Attempting to move the class assignment to the DIV containing the directive did not yield the desired result.

<div *ngIf="decoded; then coordinates" class="section"></div>
<ng-template #coordinates>
  <div>...</div>
</ng-template>

The entire outer DIV disappears and gets replaced by the contents of the template. This issue is bothersome because it forces me to include an extra DIV around everything in my template when multiple components are involved. (Additionally, it strikes me as strange that we can't preserve any properties of the tag used with *ngIf, and instead, we can use any random one, while it works differently for *ngFor.)

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates>
  <div class="section">
    <div>...</div>
    <span>...</span>
    <bzz>...</bzz>
  </div>
</ng-template>

My attempt to trick the browser by setting the class on the template failed since the template isn't actually rendered in the DOM as intended.

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates class="section">
  <div...</div>
</ng-template>

Is there a way to ensure that the DIV with the conditional directive maintains its class when rendered based on the template's contents?

Answer №1

To achieve the desired functionality, consider using the ng-container element in conjunction with the *ngIf directive.

<div class="container">
  <ng-container *ngIf="condition; then content"></ng-container>
</div>

<ng-template #content>
  <div>...</div>
</ng-template>

Answer №2

In Summary: Angular is following your instructions as given; when you utilized then, you directed it to display something other than the element the directive was placed on in the true condition. If that's not the desired outcome, adjust accordingly.


Structural directives like *ngIf and *ngFor are essentially shortcuts that are expanded upon (previously referred to as "desugaring"), see examples at https://angular.io/guide/structural-directives or more precisely at https://angular.io/api/common/NgIf#description:

Simplified form with shorthand syntax:

<div *ngIf="condition">Content to show when condition is met.</div>

Simplified form with expanded syntax:

<ng-template [ngIf]="condition">
    <div>Content to render when condition is true.</div>
</ng-template>

Note that all content is encapsulated within ng-templates for conditional rendering purposes.


If your template had been written as follows:

<div *ngIf="decoded" class="section">...</div>

it would be expanded to:

<ng-template [ngIf]="decoded">
  <div class="section">...</div>
</ng-template>

and what actually appears on screen is:

<div class="section">...</div>

Note that the class remains intact, consistent with behavior seen in other structural directives.


However, by using then, the shorthand approach:

<div *ngIf="decoded; then coordinates" class="section"></div>
<ng-template #coordinates>
  <div>...</div>
</ng-template>

is now expanded to:

<ng-template [ngIf]="decoded" [ngIfThen]="coordinates">
  <div class="section"></div>
</ng-template>
<ng-template #coordinates>
  <div>...</div>
</ng-template>

The content within the first ng-template is no longer relevant, as it will not be displayed in either scenario. It will instead showcase the content of the #coordinates template or remain empty, resulting in:

<div>...</div>

leading to disappearance of the applied class. Yet this aligns with your intentions; the purpose of then is to not present the element with *ngIf, if proven true, but rather exhibit an alternative content.


For further insight into these foundational ng- elements, check out my blog post Angular's "ng-" elements.

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

Reduce the file size of CSS and JS files for Magento

We are facing an issue with minifying CSS and Javascript for our Magento website. Currently, the size of our website is 1.1 MB and we aim to reduce it to 1 MB or even lower if possible. I tried using the "CSS Settings" and "Javascript Settings" functions ...

Unfortunately, the jquery Calendar plugin is malfunctioning

After much consideration, I decided to implement this calendar plugin on my website Plugin Unfortunately, it isn't working as expected. I am encountering the following error: $(...).pignoseCalendar is not a function at HTMLDocument. (Index ...

Error encountered when attempting to implement Material Angular 2 autocomplete functionality

I encountered an issue with Angular 2 while integrating autocomplete in material design. This is my first attempt at implementing it along with practicing backend ASP.net Core. Despite trying to install some ng2 libraries, I still couldn't get it to w ...

Unable to present the information due to a codeigniter error in retrieving the data

Encountering an issue where the data cannot be displayed and it's showing an error message of undefined variable: avg. Below is the script being used: The controller function: public function rate_config() { $rt = $_POST['hasil_rating&a ...

Ways to implement varying hover color effects on distinct list items using CSS

When I created a ul inside a nav tag, I wanted to apply different background-color hover effects to different li elements. However, the hover effect is only being applied to the anchor tags and not the complete li elements. The CSS properties that I have ...

What is the method to reduce the gap between the label and field in Vuetify input controls?

Consider a custom Vuetify text field as an example (Playground) <template> <v-app> <v-container> <v-text-field label="label goes here" variant="plain" density="compact" ...

Converting JSP email text into HTML format with Spring's formatting features

Currently, I am working on implementing an email service using Spring. Users have the ability to input the email subject and body in a form and send the email successfully. However, there is an issue where line breaks and tabs entered by the user are not b ...

How can I transform a Firestore collection into an array?

I'm struggling with converting the data retrieved from Firestore into an array that can be used for a chart.js graph. Retrieving Data from Firestore fetchData(){ //Get data this.updatesCollection = this.afs.collection(pathStats); this. ...

Struggling with getting the tabbed slider carousel to function properly in Bootstrap 4?

I attempted to incorporate this code snippet: The only modification I made was using these imports: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootst ...

The Angular Table row mysteriously vanishes once it has been edited

Utilizing ng-repeat within a table to dynamically generate content brings about the option to interact with and manage the table contents such as edit and delete. A challenge arises when editing and saving a row causes it to disappear. Attempts were made ...

UI binder is having difficulty resolving CSS

After creating a search panel for my application using UI binder, I noticed that the desired behavior is not being achieved. Ui.xml <g:HTMLPanel> <c:SimpleContainer> <c:InfoContainerHeader text="{labels.searchFilter}" /> ...

Diagram with Cascading Style Sheets and Hypertext Markup Language

As I work on creating a flowchart, here is the code that I have developed: #flowchart { width: 580px; text-align: center; font-family: sans-serif; font-size: .8em; margin: auto; } #flowchart a { ...

Tips for aligning multiple apex pie charts side by side

I am currently utilizing ReactApexChart to display pie charts in a React application. I am trying to have four pie charts aligned horizontally within a single div, but by default, the charts are displayed vertically with each chart in its own separate di ...

Retrieve information using Observables just once in Angular 2

One of my Angular 2 components relies on a service that fetches customer data from a Web API and returns an Observable: getCustomers() { return this.http .get(this.baseURI + this.url) .map((r: Response) => { let a = r.jso ...

Tips for retrieving the generated ID from the server immediately following form submission using the Post method in TypeScript

When submitting a long-form, it is important to ensure that no data is lost. Users should be able to stay on the same page to make any necessary changes after clicking the submit button. I need to receive the unique id generated by the server upon submissi ...

What is the best way to determine the highest value?

How can I ensure that the data is displayed based on the condition c.date <= this.selectedReport.report_date? The current code snippet if (Math.max(...this.costs.map(c => c.date))){} seems to be causing an issue where no data is being displayed. What ...

Bootstrap causing issues with file uploads

Using Bootstrap 4.0.0 <div class="container"> <div class="jumbotron mt-3" style="padding: 0.6em 1.6em;"> <h4>File Uploader</h4> <form enctype="multipart/form-data" action="/myurl/?action=upload" method="POST"> ...

`Month filter functionality optimized`

I have a flirty plugin installed on my website and it's working great except for one thing: I'd like the month category to be filtered in chronological order instead of alphabetically. Is there a way to achieve this? In simpler terms, how can I ...

Trouble Getting formGroup to Function Properly with Radio Button in Angular 2

Is there a way to pass the rating value from my template to my component without using parameter passing in a method? Currently, I am passing it as a parameter in the following manner: <form [formGroup]="ratingForm"> <div *ngFor=" ...

Mastering intricate CSS customization

The situation I have a specific issue with CSS that I need help with. I am currently working on customizing the user interface of our Zimbra deployment, which uses jetty (a platform I am not very familiar with). I have come across two files that seem to b ...