Override or opt-out from Angular 2 directive/component compilation

223 Views Asked by At

The question considers any environment where components should be compiled on application-wide condition (platform-dependent builds). Thus the solution may borrow mocking techniques from Angular 2 testing but should be applied to production (including AoT).

Considering that we have an existing client-side browser application, we may want to disable the compilation some of components on other platforms or override the components entirely (Angular Universal server-side rendering or mobile application).

Some of directives and components shouldn't be compiled on the other platform, because they are undesirable. I.e

  <client-side-only>fallback HTML contents</client-side-only>

should remain unchanged after application initialization.

It is necessary to cover two cases:

  • Prevent directive/component compilation
  • Override a directive/component with a replacement or a stub that has same selector

In AngularJS, it would be as easy as conditionally adding a directive to the app and using it wherever needed:

.directive('clientSideOnly', () => ({ terminal: true, priority: 10000 }));

Or modifying the behaviour of defined components/directives with decorator:

.decorator('clientSideOnlyComponentDirective', ($delegate) => ...));

Are there counterparts of these Angular 1.x tricks in Angular 2?

How can directives and components be overridden or prevented from compilation in Angular 2 with minimum amount of WET code?

0

There are 0 best solutions below