首页 > 解决方案 > 如何将 svg 水以角度填充动态

问题描述

这是代码:https ://stackblitz.com/edit/angular-cyqdzy?file=src/app/app.component.ts

html

打字稿

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 + '%';
    }
  }

有 3 个项目,那么我在这里要做的是使其动态化,例如第一个项目/水 50.9,然后如果第二个项目是 52.9,那么它将显示在第一个项目上,那么它应该是 52.9。

错误在这里是它将获取最后一个数据,它不会根据索引显示。 在此处输入图像描述

标签: javascripttypescript

解决方案


我建议添加一个管道以使代码更清晰

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

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

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

}

然后你可以使用:

<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>

ps 如果你使用<defs>标签,记得为每个定义使用一个id,否则你将永远使用相同的填充!

我为你添加了一个堆栈闪电战:

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


推荐阅读