Using BEM With Angular

Dina Elghndour
3 min readAug 1, 2019

NOTE: If you don’t hear before about BEM please read the attached link below before you start -> BEM for beginner

Hello everyone 👋

Today we will talking about how to implement BEM methodology with frameworks and I will start with Angular

Angular allows you to implement style encapsulation concept, so you might wonder if it is still necessary to use BEM since Angular allows scoped styling based on every component ?!

The answer is yes it also increases the re-usability concept in Angular
now how to do that?

we will imagine that we will build a new website so i need to prepare a component for the buttons hold all it’s styles like ( default— primary — secondary- outline …. ) and so on till cover all the buttons cases on my website

1-create new Angular app :

ng new Angular-bem-app

2-generate button component

ng g c button

3-write button html content

button.html
  • so we put [ngClass] to toggle the changes that will affect on the button when we use it in another component later
  • and for <ng-content></ng-content> it allow us to put our custom text for every button like :

<app-button>Click here</app-button>

4-now to the magical part .. our .ts file to render the classMap

button.ts
  • Here we care about classMap .. First of all we need to create @Input as much as we need in our buttons styles for example on the assumption we need a color — disabled — outline buttons
  • in Color -> put all your needs for basics solid buttons (primary-danger …)
  • in disable and outline all we need is to toggle if you need that mode or not so true or false is perfect here

after that we made a function that will update our button component class map ( updateClassMap() ) and trigger it on every change in (ngOnChanges) hook at that point the power of BEM comes finally :)

  • this.rootClass is hold ‘app-button’ text to represent our BLOKE
  • (— color, — outline, — disabled) is represent our MODIFIERS

5-the last step before using our component is the style

button.scss

try to write outline styles by your own ;)

This style means when you use your button component like that

<app-button color=”success”>Success</app-button>

the class map will convert it that to 👇

<app-button class=” app-button app-button — success”></app-button>

Examples:

<app-button color=”primary”>Primary</app-button>

<app-button color=”success”>Success</app-button>

<app-button color=”disabled” [disabled]=”true”>Disabled</app-button>

<app-button color=”danger”>Danger!</app-button>

<app-button color=”success” [outline]=”true”>Outline</app-button>

Now it’s your time to try that ;)

Thank you for reading, if you have any comments let me know, please :)

That’s all for today see you soon in my next story …👋

--

--