2
\$\begingroup\$

I am trying to get a good clean way to do CSS Encapsulation in Angular JS. The main goal of this is to use isolated components. This is what I have come up with so far.

The method I am using is something I have seen used with React Native.

You define a JavaScript object and place all your styling in the object and apply the styles to the template directly, in this case using ng-style.

JavaScript

styles = {
    background: 'green',
    color: 'black'
  };

HTML

<div ng-style="$ctrl.styles">
    My Component with local CSS
</div>

My main concern is if it will scale I believe it will as you can place the styles object into a service and inject into anywhere needed.

In theory this opens the door to mixins through lodash's _.defaults, theme changes through state changes and a lot of different options.

I'm just reviewing this before I consider it a viable option.

//Component

class myComponent {
    constructor( myCSSService ) {
        this.styles = {
            background: 'black',
            color: 'white'
        };
        this.myCSSService = myCSSService;
    }
}

myComponent.$inject = [ 'myCSSService' ];

angular.module( 'myModule', [] )
    .component( 'myComponent', {
        controller: myComponent,
        bindings: {},
        template: `
          <div ng-style="$ctrl.styles">
            My Component with local CSS
          </div>
          <div ng-style="$ctrl.myCSSService.styles">
            My Component with Injected CSS
          </div>
        `,
    } );

//Style Service

class myCSSService{
  constructor( ) {
      this.styles = {
        background: 'green',
        color: 'black'
      };
  }
}

angular.module( 'myCSSModule', [] )
    .service( 'myCSSService', myCSSService );
\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.