Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138221

Draw an object in template using Angular directive

$
0
0

I would like to use a directive to draw a triangle above a serie of div

I have four squares and two values : charge and normal

charge is used to determine the color of squares. normal to draw triangle

I have created a directive to make that

import { Directive, ElementRef, HostListener, Renderer2, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[squareChart]'
})
export class SquareChartDirective implements OnInit {
  colors = {
    1: '#13a09b',
    2: '#13a03c',
    3: '#eceb1d',
    4: '#d40f0f'
  };
  @Input() charge: number;
  @Input() normal: number;
  constructor(private el: ElementRef, private renderer: Renderer2) {}
  ngOnInit() {
    this.highlight(this.charge);
  }
  private highlight(charge: number) {
    let colorCode = Math.trunc(charge / 25) + 1;
    for (let i = 1; i <= colorCode; i++) {
      if (this.el.nativeElement.id === `sqr${i}`) {
        this.el.nativeElement.style.backgroundColor = this.colors[i];
      }
    }
  }
}

My component

<div class="container">
  <div class="row">
    <div squareChart id="sqr1" [charge]="actualCharge" [normal]="norm" class="p-2 bd-highlight square">
    </div>
    <div squareChart id="sqr2" [charge]="actualCharge" [normal]="norm" class="p-2 bd-highlight square">
    </div>
    <div squareChart id="sqr3" [charge]="actualCharge" [normal]="norm" class="p-2 bd-highlight square">
    </div>
    <div squareChart id="sqr4" [charge]="actualCharge" [normal]="norm" class="p-2 bd-highlight square">
      </div>
  </div>
</div>

For example is norm = 60 the down triangle should be above the third square ( if 25 so above second etc.. )

Example

enter image description here

I don't see how to do it from the same directive.

Another solution could be have a first row for triangles and a second row for squares but I don't think it's the best choice.

Here's demo


Viewing all articles
Browse latest Browse all 138221

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>