Milad
Milad

Reputation: 28610

Angular2 proper way to get element/component styles

There are couple of ways to get styles from an element in Angular2 :

Let say you're inside a component or a directive :

1- using nativeElement :

    let color = elementRef.nativeElement.style.color;

However , this is not recommended because you don't want to access the nativeElement directly if you're aiming to use something like a web worker in the future.

2- Using Ruler :

    this.domAdapter = new browser.BrowserDomAdapter();
    this.ruler      = new Ruler( this.domAdapter );
    this
        .ruler
        .measure( this.elementRef )
        .then( ( rect ) => {
           // Now we have access to height and width and left and top 
        } );

This is cool , but ruler wont give me the color , or any other styles , basically the ruler only gives the Rectangle (which is the Element.getBoundingClientRect() basically) .

And also , we can't use Renderer to get element styles , it only provides methods to set styles.

Upvotes: 8

Views: 4263

Answers (1)

Milad
Milad

Reputation: 28610

This is a possible answer that I'm giving , it might not be correct but this is by far what I've got :

Possible answer :

Just looked into the Ruler class and realized it's using DomAdapter and it passes native element to get the rectangle.

   // This is native Angular2 source code : 
   var clntRect = this.domAdapter.getBoundingClientRect(el.nativeElement);

I think this means if we want to get styles, we can use domAdapter like :

   let color = this.domAdapter.getStyle( this.elementRef.nativeElement , 'color' )

As we can see , domAdapter is providing getStyles method, so that should be it hopefully !!

I'll provide more concise information as I'm going and googling and investigating.

Upvotes: 2

Related Questions