how to implement dynamic water fill effects using SVG in an Angular application

Take a look at the code snippet here

HTML

TypeScript

data = [
  {
    name: 'server1',
    humidity: '50.9'
  },
  {
    name: 'server2',
    humidity: '52.9',
  },
  {
    name: 'server3',
    humidity: '53.9',
  }
]
  humidityPercentage: any;
  constructor() { }

  ngOnInit() {


    for (let x = 0; x <= this.data.length; x++) {
      this.humidityPercentage = this.data[x].humidity + '%';
    }
  }

The goal here is to make the displayed data dynamic based on the index. For example, if the first item has a humidity of 50.9, it should display as 50.9.

The current issue is that it only displays the last data and does not take into account the index. https://i.stack.imgur.com/i5FWY.png

Answer №1

One suggestion for improving the code readability is to implement a pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'humidityPipe'
})
export class HumidityPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return  value + '%' ;
  }

}

Once you have created the pipe, you can utilize it in your template like this:

<div *ngFor="let item of data;let i = index">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewbox="0 0 30 42" aria-hidden="true"
    attr.fill="url(#color-{{i}})">
    <defs>
        <linearGradient id="color-{{i}}" x1="0%" y1="100%" x2="0%" y2="0%">
            <stop offset="0%" stop-color="rgb(132, 219, 255)" />
            <stop [attr.offset]="item.humidity | humidityPipe" stop-color="rgb(132, 219, 255)" />
            <stop [attr.offset]="item.humidity | humidityPipe" stop-color="rgb(255, 255, 255)" />
            <stop offset="100%" stop-color="rgb(255, 255, 255)" />
        </linearGradient>
    </defs>

    <g transform="translate(35,65)">
        <path id="scale" stroke="#000" stroke-width="1.5" d="M15 3
                            Q20.5 12.8 40 35
                            A28.8 28.8 0 1 1 0 30
                            Q20.5 12.8 15 3z" />
    </g>
</svg>

If you are using <defs> tags, make sure to assign a unique id to each definition to avoid unintended consequences!

I have also included a stackblitz link for your reference:

https://stackblitz.com/edit/angular-ymupuk

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

Discovering the value of a chosen star and saving it in a database with the help of jQuery or JavaScript

When a user clicks on the 3rd star in the Jrate Plugin, I need to retrieve the value of 3. This can be achieved using the jRate onSet option. Below is my HTML: <div id="jRate"></div> And this is my JavaScript code: $("#jRate").jRate({ ...

Organize an array of JSON objects based on a specific key and eliminate any duplicated entries

I am grappling with the challenge of grouping an array of JSON objects by the id_commande attribute and eliminating any duplicates. I am finding it quite perplexing to figure out a solution to this issue without relying on a library like lodash. Ideally, I ...

An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials. The error is puzzling as it displays the popup error message, but still manages to register the token and s ...

What is the best way to transfer information from df ~ to my webpage?

I'm currently working on a pie chart that visualizes the disk space usage on my Linux machine. I need help figuring out how to properly parse this data onto a microservice URL. Any assistance would be greatly appreciated. Here's what I have so f ...

Enable the generation of scss.d.ts files with Next.js

I'm currently working on a project that requires the generation of .d.ts files for the scss it produces. Instead of manually creating these files, I have integrated css-modules-typescript-loader with Storybook to automate this process. However, I am ...

Hide the external div if the tab is active in Angular Bootstrap

How can I determine if a specific tab is active and then hide a div outside all tabs when it is active? Plunker: https://plnkr.co/edit/b9O9S7JxxgzhQKcKONkn?p=preview <div class="border"> Conceal me when Tab #3 is active. </div> < ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...

What is the best way to display an Error 404 page in a statically rendered client-side page using Next.js?

import { onAuthStateChanged } from "firebase/auth"; import Link from "next/link"; import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import { auth } from "../../lib/firebase&qu ...

Trouble with installing Enmap due to better-sqlite3 error

For a while now, I've been struggling to get enmap installed. Despite searching the web exhaustively, I haven't come across any solutions that work for me. Every time I try npm i enmap, I consistently encounter this frustrating error: One part o ...

Are there any limitations imposed on keydown events in JavaScript when attempting to modify the browser's

I attempted to implement a JavaScript keydown event that would refresh the page, but unfortunately, it did not function as intended. Interestingly, the same code works flawlessly when triggered by a button click event. I'm in search of a solution to r ...

Steps for successfully passing an object in a dynamically generated function invocation

In my jQuery script, I have a click event bound to thumbnail images with the class "thumbnail": $(".thumbnail").click(function(){ var obj = new Object(); obj.el = "imageEdit"; obj.id = $(this).attr("id").replace("img_",""); openDialogue(obj); }); ...

Creating an index signature in TypeScript without having to use union types for the values - a comprehensive guide

Is it possible to define an index signature with strict type constraints in TypeScript? interface Foo { [index: string]: number | string } However, I require the value type to be either number or string specifically, not a union of both types (number | ...

Photos failing to load in the image slider

Although it may seem intimidating, a large portion of the code is repetitive. Experiment by clicking on the red buttons. <body> <ul id="carousel" class="carousel"> <button id="moveSlideLeft" class="moveSlide moveSlideLeft"></button& ...

When a user clicks on a React listItem, the information for that specific item is displayed using

As a beginner in the coding world, I am currently learning about React and JSON. My project involves working on three interconnected panels. Specifically, I aim to showcase checklist answers on the third panel. First Panel: Displaying: All the ESN ("46 ...

Navigate to a new webpage using a string of characters as a legitimate web address

When a user performs a search, I pass the search term as a string to direct them to a new page. How can I create a valid URL (e.g., remove spaces from the string)? It's crucial that the next page can recognize where any spaces were in the search word ...

Issue with styling Icon Menu in material-ui

I'm having trouble styling the Icon Menu, even when I try using listStyle or menuStyle. I simply need to adjust the position like this: It currently looks like this: Update: Here's an example: import React from 'react'; import IconM ...

The PHP server is having trouble accepting a JavaScript object sent via AJAX

Hey there, I'm currently facing an issue with sending fields from a form saved in a JavaScript object to a PHP server. I have set up the AJAX communication, but when I try to access the object in PHP, I notice that the length is showing as 0 during de ...

Challenges encountered when passing objects with Angular 2 promises

I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.compon ...

Guide on implementing text/ng-template script section in jsfiddle

My current challenge involves creating a jsfiddle that utilizes AngularJS to display two calendar controls. While my code functions properly when run locally, I've encountered an issue with including the template code via a script tag on jsfiddle: ht ...

The Vuetify Jest button trigger fails to function properly despite utilizing a spy

Recently delved into the world of Vue.js and Jest to see how they interact. I watched some tutorials and then decided to give it a go myself, but ran into trouble with getting the trigger click to work. Within my component, I have a login button, which is ...