Angular does not display results when using InnerHtml

I'm currently in the process of creating a weather application with Angular, where I need to display different icons based on the weather data received. To achieve this functionality, I have developed a function that determines the appropriate icon to display:

  icon(icon: any) {
    switch (icon) {
      case 'rain' :
        return '<i class="icon-basecloud"></i><i class="icon-rainy"></i>';
        break;
      case 'cloudy' :
        return '<i class="icon-basecloud"></i><i class="icon-cloud"></i>';
        break;
      case 'partly-cloudy-day' :
        return '<i class="icon-sunny-cloud"></i><i class="icon-sunny-cloud-sunny"></i>';
        break;
      case 'partly-cloudy-night' :
        return '<i class="icon-basecloud"></i><i class="icon-night"></i>';
        break;
      case 'clear-day' :
        return '<i class="icon-day"></i>';
        break;
      case 'clear-night' :
        return '<i class="icon-night"></i>';
        break;
      default:
        return '<i class="icon-basecloud"></i><i class="icon-rainy"></i>';
    }
  }

However, when attempting to incorporate this function within an innerHtml attribute, the icons did not display as expected.

<div [innerHTML]="icon(temps.currently.icon)"></div>

Upon inspecting the elements, I noticed that the icons were being rendered but not shown on the page. This led me to suspect that there may be an issue related to CSS styling for the icons, as using innerHtml for other types of content, such as images, worked perfectly fine.

Answer №1

It appears that the existing answers lack necessary details, so I will provide my own insights.

[innerHtml]="icon('rain')"

Let's analyze what is happening within the template based on the above expression. It seems like the double quotes in your class names might be causing issues by prematurely ending the template string.

If we break it down, the result could look something like

[innerHtml]="'<i class="icon-basecloud"></i><i class="icon-rainy"></i>"'

This can potentially lead to "'<i class=", creating an invalid HTML string that cannot be displayed correctly.

Therefore:

I suggest relocating your switch statement directly into the template for better structure and clarity. Consider something like this:

<div [ngSwitch]="temps.currently.icon">
    <span *ngSwitchCase="'rain'">
      <i class="icon-basecloud"></i><i class="icon-rainy"></i>
    </span>

    <span *ngSwitchCase="'cloudy'">
      <i class="icon-basecloud"></i><i class="icon-cloud"></i>
    </span>
    ... additional cases, etc
</div>

Update:

To enhance the readability further, you could create a separate reusable component for the switch statement. This component could accept an input parameter such as @Input() iconString, allowing you to display multiple icons by using multiple instances of the component. A use-case scenario could be:

<div>
  <span>Monday:<span>
  <weather-icon [iconString]="forecast['monday']"></weather-icon>
</div>

<div>
  <span>Tuesday:<span>
  <weather-icon [iconString]="forecast['tuesday']"></weather-icon>
</div>

In this case, you would have a forecast variable defined in your component.ts file.

forecast = {
 monday: 'rain',
 tuesday: 'cloudy,
 ... etc
};

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

Encountering a issue while running npm start with Angular 2 RC build

After upgrading from Angular2 beta 15 to the RC version, I encountered some errors while trying to run my application. typings/browser/ambient/es6-shim/index.d.ts(8,14): error TS2300: Duplicate identifier 'PropertyKey'. typings/browser/ambient/e ...

Activate Bootstrap button functionality with JavaScript

Hey team, I've got a Bootstrap button on my HTML page: ..... <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> ... <div class="accept-btn"> <button type="button" class="bt ...

The flex grow animation fails to activate when the Bootstrap 4 style sheet is added

Trying to implement transitions with flex grow has been a challenge. It works smoothly without any issues, but as soon as I add the bootstrap 4 style sheet, the transitions stop working. I haven't even started using the bootstrap 4 classes yet, it&apo ...

Having trouble getting the Angular2 boilerplate to start with npm?

Just starting out with Angular2 and attempting to set up the environment using the boilerplate code found at https://github.com/mschwarzmueller/angular-2-beta-boilerplate. After successfully installing my dependencies with npm install, I encountered some ...

Loop through an array of strings

When I receive the data as a string[] https://i.sstatic.net/ttyag.png However, when I attempt to loop over it subUrl(arr) { for(let i of arr) { console.log(i); } } No output is being logged. What could be causing this issue? ...

Ionic - Landscape Mode Causing Alignment Distortion

I'm currently working on designing a grid-based image display for an Ionic Mobile App. One of the main challenges I'm facing is adjusting the heights of the images based on the screen size. I want to set a maximum height for both portrait and lan ...

Adding an image within the body of text in a Django model, where both the text and image coexist

I am currently seeking a method to seamlessly insert an image within the text of my Django-powered blog. My goal is to achieve a layout similar to the one showcased in this example: https://i.stack.imgur.com/cFKgG.png The desired layout consists of two c ...

Guide to creating jest unit test for an observable variable exclusively utilized in a template resulting in the error "Property 'pipe' of undefined cannot be read"

Seeking help with creating unit tests for an Angular component that utilizes a constructor and observable variable in the HTML template. Below is the code snippet I am having issues with: voice-summary.component.ts export class VoiceSummaryComponent { v ...

Error Raised Due to Modification After Checking in Angular 2/Angular 5

Dealing with ExpressionChangedAfterItHasBeenCheckedError in Angular 2/Angular5 https://i.sstatic.net/HXSfP.png Error message: An error has occurred: ExpressionChangedAfterItHasBeenCheckedError. The expression has changed after it was checked. Previo ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

a problem with images overflowing in CSS

I am currently working on setting up a personal blog for myself, but I have encountered an issue with the overflow property. On my home page, I have a div that contains text and images for reviews. When users click on the "read more" button, the full parag ...

How can I modify the text color of the Navbar-Brand class in Bootstrap NavBar?

I have been experimenting with various options to change the text color of the `navbar` and specifically the `navbar-brand` item. However, my `.navbar-brand {color: purple;}` CSS class doesn't seem to be working. Can someone please assist me in determ ...

Achieving proper stacking of a table with other div elements

I've come across some similar inquiries, but none seem to fully address the specific issue at hand. If there's an existing thread on this that I overlooked, I apologize in advance. So, here's a multi-part problem: my solution for the first ...

Update the parent element's class style within a targeted div media query

I am facing a challenge where I want the width of my .container element to be 100% when the screen size reaches 900px. The issue is that I have used .container on multiple pages and only wish to change its appearance within the #sub-top div. The terminolo ...

Expanding on Angular's virtual scroll feature: automatically add new items as you reach the bottom of the

I'm facing a challenge in my Angular application where I want to implement virtual scroll. The items displayed on the list are the outcome of a remote paged search. My goal is to fetch more results (trigger the next page) every time I scroll down to t ...

TypeScript: Error - .map() is an Invalid Function

I have come across numerous questions similar to mine, but the vast majority of them pertain to an Observable, which is not the issue I am facing. The code snippet in question looks like this: selectedItems: Item[] = null; selectedDate: Date = null; subm ...

Semi-transparent image

Can I achieve a semi-transparent image? Similar to this gradient: background:linear-gradient(to bottom,rgb(44, 44, 44),rgb(29, 38, 51,0.322)); ...

How can I implement a button in Angular Ag Grid to delete a row in a cell render

I have included a button within a cell that I want to function as a row deleter. Upon clicking, it should remove the respective row of data and update the grid accordingly. Check out the recreation here:https://stackblitz.com/edit/row-delete-angular-btn-c ...

Utilizing the overflow feature in conjunction with a specified height

Take a look at this image, the overflow:hidden property is not working as expected and some text is still visible that I want to hide without adjusting the height. How can I achieve this? Focusing on the highlighted area in Red, it is causing irritation. ...

Safari not fully supporting CSS translate functionality

When I click a button on my app, an element slides into view and then slides out when I click the button again. This is achieved using a combination of CSS and JS. It works perfectly in Chrome and Firefox, but only partially in Safari. In Safari, the elem ...