Solution 1 :

Reference it without a hash symbol and use renderer2 to edit styles/classes.

For details please check my stackblitz sample, this are the main changes:

  constructor(private renderer: Renderer2) {}

  ngOnInit() {
    const degree = 90;
    const image = document.getElementById('image');
    this.renderer.setStyle(
      image,
      'transform',
      `rotate(${degree}deg)`
    )
  }

Problem :

I need to rotate an image in html from my component with

(document.querySelector('#image') as HTMLElement).style.transform = `rotate(${degree}deg)`;

or

document.getElementById('#image').style.transform = `rotate(${degree}deg)`;

and set an id to it here

<img id= "image" class="arrow" src = "assets/arrow.png"/>

but it crashes the page with this error

core.js:5882 ERROR TypeError: Cannot read property ‘style’ of null

Comments

Comment posted by Sandy B

How about adding a class whenever you need to rotate the element? class is predefined with rotate styles. Is it fulfill your requirement?

Comment posted by sheko

@SandyB the problem is i need to calculate the angle then update the image rotation inside the constructor of the component but it crashes

Comment posted by Sandy B

How about a stackblitz? Any chance you can set it up for reproducing the issue

Comment posted by sheko

@SandyB i’m asking is the above code is correct or not ? i searched a lot it’s strange how there is no someone to know the problem the image exists inside the html and it do rotate when i set the style inside the html but can’t from the component

Comment posted by stackblitz.com/edit/angular-cavcg4

@sheko you have to import it from

Comment posted by nullptr.t

@sheko please take a look at the stackblitz, it is working…

By