As of v9.1.0 of the Angular CLI it’s possible to have the CLI generate block components.

Setting a default value:

Via angular.json:

...
"projectType": "application",
"schematics": {
    "@schematics/angular:component": {
      "displayBlock": true
   }
 }
...

From now on any component that is being generated by the CLI will contain display: block` in the CSS file or inlined.

Via shell:

ng config schematics.@schematics/angular.component.displayBlock true

Why should I care?

There is a problem with Angular components out of the box: angular/issues/25856 respectively angular-cli/issues/12244. Components have the CSS display property set to inline implicitly by default.

Read more about inline elements: https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements

So when creating a new component without a stylesheet, or with an empty css, scss, sass, less or styl file, then what you are generating essentially is a component with the following CSS:

:host {
  display: inline
}

In most cases, this is not what you want and will result in problems further down the road. Any tool (e.g. Cypress) that relies on the width and height of elements / components will not be able to read those properties via JavaScript. This can already be experienced with the Chrome DevTools. When inspecting an inline component, the DevTools fail to highlight it correctly.

An example

Inspecting an inline component

Screenshot 2020-01-18 at 19.55.55
the element is not highlighted properly, width and height are both zero

It’s not possible to query the width or the height of the component.

Inspecting a block component

This is the exact same component, but now we are setting the display property to block:

Angular block component
width and height are returned properly

The DevTools can now correctly highlight the component and also read the width and height of the element.

Since the Angular Team made the decision not to change this, I decided it’s finally time to get the ball rolling and opened up a pull request on the angular-cli repository. The goal is to provide an ‘opt-in‘ option to circumvent this problem, at least when generating components with the CLI, by simply setting the option displayBlock.

Photo by Bailey Zindel

2 Comments

  1. I suggest setting the flag as a default of the project:

    `ng config schematics.@schematics/angular.component.displayBlock true“

    Or even as a global default:

    `ng config –global schematics.@schematics/angular.component.displayBlock true`

    • That’s exactly what I’m suggesting.

      Thanks for the hint to set the property via the command line.

      Cheers!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: