Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 proper way to get element/component styles

Tags:

angular

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.

like image 633
Milad Avatar asked May 17 '16 03:05

Milad


People also ask

What are the two component decorator metadata properties used to set up CSS styles for a component?

You have used both styles and styleUrls metadata properties to style your component's HTML template.

Is ng deep deprecated?

Both APIs ::ng-deep and /deep/ are deprecated and will eventually be removed in the future.


1 Answers

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.

like image 101
Milad Avatar answered Nov 07 '22 07:11

Milad