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

Getting the value of a hidden input field within a div by accessing the event.target that initiated the event in JavaScript

I am working with a set of li elements, each containing specific child elements structured like this: <li class="list"> <!--Parent--> <input type="hidden" id="id" value="3"> <!--Child 1--> <div class="cd-1">....</div ...

Is there a way for me to streamline the process of logging in using either Google or Facebook?

Is there a way for me to automate the scenario if I'm unable to locate the element using Appium Uiautomator? https://i.stack.imgur.com/Rjji4.png ...

Storing Vue.js components as objects in a database: A step-by-step guide

Is there a way to serialize Vue.js components and store them in a database? For example, I am looking to save components like the HelloWorld component typically found in a fresh Vue installation. Any suggestions on a serialization process or package that ...

The chaotic world of Android WebKit versions 2.x and 3.x

I have been working on an Android app and my goal is to make it compatible with Android versions 2.2 and above. Currently, due to issues with the WebView control, I am restricted to targeting Android 4.0 and higher. The app primarily uses HTML, CSS, Java ...

The list filter may not work properly if the search string is left blank

I am currently working on a list filtering feature that updates based on user input. As the user types, the system compares the entered text against the items in the list and displays the matching objects in an array. However, I'm facing an issue - wh ...

Transferring data through Ajax, Jquery, and PHP: A seamless process

My goal is to develop an attendance button that adds +1 to the total number of people attending when clicked by the user. I am looking for a way to achieve this without having to refresh the page. Ideally, I would like to connect it to a database to upda ...

Enhancing the appearance of individual cells within an HTML table by applying custom classes

I'm in the process of automating report generation for my organization. Our workflow involves using R to summarize data from Excel, then utilizing Rmarkdown, knitr, and the "htmlTable" package to generate HTML files. Currently, I am implementing CSS ...

Tips for managing onChange events in TypeScript

I'm still learning Typescript and I have a question regarding handling the onChange event in a TextField component when using Typescript. Can you provide guidance on how to approach this? I currently have a function called handleChangeDate(e: React. ...

Accessing an object within an array in a Node.js EJS file

Great job everyone! I've developed a project using Node.js which includes the following schema structure: const debt = new Schema({ name: { type: String, required: true, }, medicine: [{ data: { type: Schema.Types.ObjectId, ...

Vue - Unable to navigate to a different route

I just started working with Vue and attempted to redirect '/home' to '/travel', but for some reason it's not functioning correctly. Can someone please guide me on how to achieve this? What could be the issue with my code? Thank y ...

Collaborative service utilization in Angular 2

My goal is to create a shared service for my app. import { Injectable } from '@angular/core'; @Injectable() export class SharedService { testService() { console.log('share!'); } } However, when I attempt to inject this shared ...

How do I send multiple values from a child to a parent in Vue.js, while also passing another parameter in the parent's v-on event?

Behold, a demonstration of code. Vue.component('button-counter', { template: '<button v-on:click="emit_event">button</button>', methods: { emit_event: function () { this.$emit('change', 'v1&apos ...

What is the best way to manage a significant volume of "business" data or objects within my JavaScript project?

I specialize in working with AngularJs and have a factory that provides services related to buildings. I am managing a large number of buildings (around 50-60) with multiple properties and sub-properties associated with each one (approximately 15-20, some ...

Variable assigned by Ajax no longer accessible post-assignment

Recently, I've written a script to fetch data from a SQL database and now I'm in the process of creating a JS wrapper for it. Utilizing certain functions, I call the script and extract information from the DB as soon as it becomes available. var ...

What is the reason behind the TypeScript HttpClient attempting to interpret a plain text string as JSON data?

When utilizing Angular TypeScript, I have implemented the following approach to send a POST request. This request requires a string parameter and returns a string as the response. sendPostRequest(postData: string): Observable<string> { let header: ...

Issues have been identified with the functionality of the Am charts v3 XY in conjunction with a

I'm currently working on a project with angularJS and utilizing the npm package amcharts3 "^3.21.15". I've encountered a minor issue regarding the logarithmic scale in my XY chart. Below is my chart without the logarithmic scale: View working ch ...

Error: The object referenced does not have a function called 'findById' within its methods when trying to export

I have come across a number of similar questions on this platform, but most of them seem to be related to HTML. My issue involves encountering an error while submitting a login form in Java. Here is a Very Simple Save Function: var model = require(' ...

Reviving jQuery Smooth Zoom Pan viewer following container resize

I am in the process of developing a responsive image viewer and have decided to incorporate the Smooth Zoom Pan plugin for enhanced pan/zoom functionality. Within my layout, I have two primary panels: the viewer container and a controls container that are ...

What is the reason for not storing information from MySQL?

Looking to extract data from a website using this JavaScript code. var i = 0 var oldValue = -1 var interval = setInterval(get, 3000); function get(){ var x= $($('.table-body')[1]).find('.h-col-1') if(i!=5){ if(oldValue != x){ old ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...