0

I am attempting to create a circular arrangement of links using Angular 2. I have a function that sets the fixed location of the style.left and style.top for each link, based on the number of links in the circle. I've attempted to use this code in the constructor of my component, but Angular fails to build, giving me an error that the items.length property is null.

Here's my component class code which is a mix of typescript and javascript:

export class PlayersComponent {
items: any;
constructor() {
  this.items = document.querySelector('.circle');
  for(var i = 0, l = this.items.length; i < l; i++){
    this.items[i].style.left = (50 - 35*Math.cos(-0.5 * Math.PI - 2*(1/l)*i*Math.PI)).toFixed(4) + "%";
    this.items[i].style.top = (50 + 35*Math.sin(-0.5 * Math.PI - 2*(1/l)*i*Math.PI)).toFixed(4) + "%";
  }
}
rptwsthi
  • 10,094
  • 10
  • 68
  • 109
MaxImpact
  • 5
  • 1
  • 2
  • 3
    Just a side note, the constructor is used for dependency injection not for doing the 'work' you should be doing this within ngOnInit(); see here: http://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit – Code Ratchet Jan 20 '17 at 05:25
  • 1
    It is also a mix of angular and not angular. Please read the guides how to program with angular – smnbbrv Jan 20 '17 at 05:29
  • You should style binding instead `[style.left.px]="styleValues[index]"` or `ngStyle` – Günter Zöchbauer Jan 20 '17 at 06:36

1 Answers1

0

Instead of accessing element inside constructor.You have to implement AfterViewInit and access element inside ngAfterViewInit method.

DOM is initialize after viewInit.Please check here

Refer the following code:

import {Component,AfterViewInit} from '@angular/core'; 
export class PlayersComponent implements AfterViewInit{
  items: any;
  ngAfterViewInit() {
     this.items = document.querySelector('.circle');
     for(var i = 0, l = this.items.length; i < l; i++){
        this.items[i].style.left = (50 - 35*Math.cos(-0.5 * Math.PI - 2(1/l)*i*Math.PI)).toFixed(4) + "%";
        this.items[i].style.top = (50 + 35*Math.sin(-0.5 * Math.PI - 2*(1/l)*i*Math.PI)).toFixed(4) + "%";
  }
}

Please mark it as answer if it helps!!!

Binal Vekariya
  • 250
  • 1
  • 11