<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daniel Bojarski on Medium]]></title>
        <description><![CDATA[Stories by Daniel Bojarski on Medium]]></description>
        <link>https://medium.com/@daniel.bojarski.db?source=rss-c5f8a5ab98e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NjPHLqthAoCBA_rF</url>
            <title>Stories by Daniel Bojarski on Medium</title>
            <link>https://medium.com/@daniel.bojarski.db?source=rss-c5f8a5ab98e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 15:45:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daniel.bojarski.db/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Befriend ngDoCheck, it’s not its fault]]></title>
            <link>https://medium.com/@daniel.bojarski.db/befriend-ngdocheck-its-not-its-fault-90764a886cba?source=rss-c5f8a5ab98e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/90764a886cba</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Daniel Bojarski]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 00:39:01 GMT</pubDate>
            <atom:updated>2024-02-01T07:29:12.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dYJQSUIxH4Wnlsk-" /><figcaption>Photo by <a href="https://unsplash.com/@fakurian?utm_source=medium&amp;utm_medium=referral">Milad Fakurian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s dive a little into change detection and Angular source code representing this mechanism. Why Angular calls it 2–4 times?</p><p>This article is not about explaining in depth how change detection works in Angular because everything about updating particular component subtree has been widely described in <a href="https://angular.io/guide/change-detection">Angular Documentation</a> and <a href="https://angularindepth.com/posts/1131/if-you-think-ngdocheck-means-your-component-is-being-checked-read-this-article">Angular in Depth blog article</a>.</p><h4>ngDoCheck — what the ©heck is it?</h4><p><em>ngDoCheck</em> is just a hook, a component lifecycle method, same as <em>ngOnInit</em>, <em>ngAfterViewInit</em>, <em>ngOnChanges</em> etc. The difference is that this hook is being called after every change detection cycle and after <em>ngOnInit</em> or <em>ngOnChanges</em>. Itself it does nothing as every other hook does nothing without content inside.</p><h4>Why does it exist in the first place?</h4><p>The main key of this hook is to inform a component that change detection cycle has been run and if you want to do something with it, do it now. Change detection will run independently on component’s change detection strategy. The strategy tells Angular whether such component should be checked in terms of any change or not. So if your component has <em>OnPush</em> change detection strategy and change detection cycle has been run by anything, <em>ngDoCheck</em> will still fire and inside this method you can conditionally call <em>markForCheck</em> for this component. So, still despite having <em>OnPush</em> you can implement your own change detection strategy for this component.</p><pre>@Component({<br>  template: `<br>    &lt;!-- click event as many events is intercepted by Zone.js and is treated<br>      as one of many change detection triggers --&gt;<br>    &lt;button (click)=&quot;null&quot;&gt;trigger change detection&lt;/button&gt;<br>    &lt;app-child&gt;&lt;/app-child&gt;<br>  `<br>})<br>class Parent {}<br><br>@Component({<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>class Child implements DoCheck {<br>  ngDoCheck() {<br>    // In this case it fires on event from parent.<br>    // Don&#39;t get me wrong. Child component view<br>    // will not be rerendered as nothing that could break the OnPush strategy<br>    // hasn&#39;t happened. But still you have the oportunity to do here<br>    // this.changeDetectorRef.markForCheck() to tell the Angular to verify<br>    // app-child view<br>  }<br>}</pre><p>If you want more meaningful use case, imagine having an object as <em>Input()</em>. If parent component instead of changing the whole object modifies just a key e.g <em>obj.x = true</em>, Angular will not detect input change and will not check the component. The reason is that object reference has not changed so it’s being treated as the same value. So, parent changed a key of an object and called <em>markForCheck</em> or did the assignment as a reaction to an event or inside micro task e.g. <em>setTimeout</em> — parent changed the key in any way triggering Angular change detection cycle — <em>ngDoCheck</em> fired in child component which now can call its own <em>markForCheck</em>. In short — it can react as if the input changed.</p><pre>@Component({<br>  template: `<br>    &lt;button (click)=&quot;user.role = &#39;admin&#39;&quot;&gt;trigger change detection&lt;/button&gt;<br>    &lt;app-child [user]=&quot;user&quot;&gt;&lt;/app-child&gt;<br>  `<br>})<br>class Parent {<br>  user = { name: &quot;Daniel&quot;, role: &quot;moderator&quot; };<br>}<br><br>@Component({<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>class Child implements DoCheck {<br>  @Input() user: { name: string, role: string }<br>  <br>  previousRole: string<br><br>  constructor(private changeDetectorRef: ChangeDetectorRef) {}<br><br>  ngOnInit() {<br>    this.previousRole = this.user.role<br>  }<br><br>  ngDoCheck() {<br>    if (this.user.role !== this.previousRole) {<br>      // If Child had other nested component with OnPush strategy, markForCheck<br>      // will call its ngDoCheck where in need you can use markForCheck and so<br>      // on as deep in the components tree as you want<br>      this.changeDetectorRef.markForCheck()<br>    }<br>  }<br>}</pre><h4>Why change ngDoCheck fires so many times?</h4><p><em>ngDoCheck</em> runs:</p><ol><li>after <em>ngOnInit</em></li><li>after each <em>ngOnChanges</em></li><li>after each change detection cycle</li></ol><p>so add <em>ngDoCheck</em> with a console.log to your component</p><pre>@Component({<br>  template: &quot;&quot;<br>})<br>class AppComponent implements DoCheck {<br>  ngDoCheck() {<br>    console.log(&quot;--- ngDoCheck ran&quot;)<br>  }<br>}</pre><p>start your application and notice this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DoKl6F1MkA8ltfXL02bSTw.png" /></figure><p>It invokes twice because of:</p><ol><li>application bootstrap</li><li>zone scheduler (stay tuned)</li></ol><h4>Application bootstrap</h4><p>Let’s see what we have in our main module which is <em>AppModule</em>.</p><pre>import { NgModule } from &#39;@angular/core&#39;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;<br><br>import { AppComponent } from &#39;./app.component&#39;<br><br>@NgModule({<br>  declarations: [<br>    AppComponent<br>  ],<br>  imports: [<br>    BrowserModule<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]  // *1<br>})<br>export class AppModule implements DoBootstrap {<br>  constructor(private applicationRef: ApplicationRef) {}<br><br>  ngDoBootstrap() {  // *2<br>    this.applicationRef.bootstrap(AppComponent)<br>  }<br>}</pre><p>You can bootstrap the application in both ways. <strong>*1</strong> and <strong>*2</strong> can be used interchangeably. In case of bootstrap array, Angular will iterate through it and call <em>ApplicationRef.bootstrap</em> with each component. In case of having <em>ngDoBootstrap</em>, Angular will just call it. <em>ngDoBootstrap</em> lets you be more flexible e.g. you can bootstrap the component under dynamic, computed selector or fetch any data before bootstrapping the app.</p><p>Now let’s get back to <strong>main.ts</strong> where our app is actually bootstrapped.</p><pre>platformBrowserDynamic().bootstrapModule(AppModule)<br>  .catch(err =&gt; console.error(err))</pre><p>If you go to Angular source code, to the <em>bootstrapModule</em> function and then inside and inside and inside and inside, you will finally find this code</p><pre>_moduleDoBootstrap(moduleRef) {<br>  const appRef = moduleRef.injector.get(ApplicationRef)<br><br>  if (moduleRef._bootstrapComponents.length &gt; 0) {<br>    moduleRef._bootstrapComponents.forEach(f =&gt; appRef.bootstrap(f))<br>  }<br>  else if (moduleRef.instance.ngDoBootstrap) {<br>    moduleRef.instance.ngDoBootstrap(appRef)<br>  }<br>  else {<br>    // ...<br>  }<br><br>  this._modules.push(moduleRef)<br>}</pre><p>Here you can see what I was talking about. But where is the additional change detection that called <em>ngDoCheck</em> second time?</p><p><strong>ApplicationRef bootstrap method</strong></p><pre>bootstrap(componentOrFactory, rootSelectorOrNode) {<br>  // ...<br>  this._loadComponent(compRef)<br>  // ...<br>}</pre><p>and its <em>_loadComponent</em></p><pre>_loadComponent(componentRef) {<br>  this.attachView(componentRef.hostView);<br>  this.tick();<br>  // ...<br>}</pre><p>Voila! <em>tick</em> is a method calling <em>detectChanges</em> on each component in component tree. We will get to full definition of <em>tick</em> quite soon. So, to recap, <em>ngDoCheck</em> is being called twice because:</p><ol><li>application has been bootstrapped and in result change detection ran for every bootstrapped component</li><li>zone scheduler (keep going)</li></ol><h4>Why template is called so many times?</h4><p>Let’s make an experiment. Revoke all changes you did in <strong>main.ts</strong>, let’s turn off production mode. Add to your component a method with <em>console.log</em> and invoke it inside component view.</p><pre>@Component({<br>  template: &quot;{{print()}}&quot;<br>})<br>class AppComponent implements DoCheck {<br>  ngDoCheck() {<br>    console.log(&quot;--- ngDoCheck ran&quot;)<br>  }<br><br>  print() {<br>    console.log(&quot;&gt;&gt;&gt; printed&quot;)<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBTipOB_3pUTP9T7CDog1g.png" /></figure><p>The view has been refreshed 4 times. It’s really bad for one empty component. It happens because Angular in development mode checks the view twice. Instruction for this is inside that <em>tick</em> method.</p><pre>tick() {<br>  // ...<br>  try {<br>    // ...<br>    for (let view of this._views) {<br>      view.detectChanges();  // *1<br>    }<br>  <br>    if (typeof ngDevMode === &#39;undefined&#39; || ngDevMode) {<br>      for (let view of this._views) {<br>        view.checkNoChanges();  // *2<br>      }<br>    }<br>  }<br>  // ...<br>}</pre><p>In <strong>*1</strong> <em>detectChanges</em> is called on each component and in <strong>*2</strong> Angular checks if nothing changed by rebuilding each view and doing comparison. Rebuild evaluates <em>print</em> method again and that’s why we see it twice. <strong>*2</strong> happens only in development mode and reason behind that is to make sure that after <strong>*1</strong> (<em>detectChanges</em> immediately updates the view) data inside view is the same in <strong>*2</strong>. If they are different, it would mean that you change something in a wrong place e.g. inside method invoked inside template.</p><pre>@Component({<br>  template: &quot;{{getTime()}}&quot;<br>})<br>class AppComponent {<br>  getTime() {<br>    return new Date().getTime(()<br>  }<br>}</pre><p>In my case after <strong>*1</strong>, view displayed “1706742824229” and immediately after it displayed “1706742824230”. Such behaviour is incorrect and Angular triggers error for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RComwc-yM2iVFY-iVpZ8kg.png" /><figcaption>Read more about this error <a href="https://angular.io/errors/NG0100">here</a></figcaption></figure><h4>Production mode</h4><p>Turning on production mode tells Angular not to reverify view which means that our <em>print</em> method will be called once per each change detection. Now we are left with 2 <em>ngDoCheck</em> and 2 <em>console logs</em>. Second change detection will not rebuild your view if you add <em>OnPush</em> strategy to the <em>AppComponent</em>. This way we have finally single and predictable template refresh and we know everything about why it was called that many times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdTTQj7qhKOhMPdfC-h5Ng.png" /></figure><h4>More in depth what happens when you bootstrap your app.</h4><p>Angular uses <em>Zone.js</em> in its change detection system. <em>Zone.js</em> overwrites or, we can say, monkey patches micro tasks such as <em>setInterval</em>, <em>setTimeout</em> etc., <em>fetch</em>, events like <em>click</em>, <em>blur</em>, <em>focus</em> and much more to inject itself inside the context and react to this. At the start, before bootstrapping the app, <em>Zone.js</em> is being initialised and listens to kickoff the change detection cycle.</p><pre>class NgZoneChangeDetectionScheduler {<br>  //...<br>  initialize() {<br>    //...<br>    this._onMicrotaskEmptySubscription = this.zone.onMicrotaskEmpty.subscribe({<br>      next: () =&gt; {<br>        this.zone.run(() =&gt; {<br>            this.applicationRef.tick()<br>        });<br>      }<br>    });<br>  }<br>  //...<br>}</pre><ol><li>Application is being created (step much earlier than bootstrapping)</li><li>Zone is initialised</li><li>Application is bootstrapped</li><li>First change detection cycle for bootstrapped component</li><li>Angular kicks off the change detection calling <em>tick</em> inside zone scheduler</li><li>Second change detection cycle</li></ol><p>At the start of the application change detection will be called twice as I previously mentioned. The process is even more interested but it’s a topic for another article.</p><h4>You can be mistaken by Angular documentation in terms of ngDoCheck frequency.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*F9tVzxLDp51gv0Rlyo2nYQ.png" /></figure><p>According to documentation <em>ngDoCheck</em> will fire after every change detection cycle. <em>tick</em> description <a href="https://angular.io/api/core/ApplicationRef#tick">says</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*_plFPcPHg0EQqP9llqtYNg.png" /></figure><p>“performs a second change detection cycle” but is it really? If <em>tick</em> would perform second change detection cycle then in development mode we would have 3 <em>ngDoCheck</em> calls.</p><ol><li>First after application bootstrap (bootstrapped component with called <em>detectChanges</em>)</li><li>Second and third after zone scheduler <em>tick</em></li></ol><p>but we have 2, not 3 because <em>tick</em> in development mode does not trigger change detection twice. Instead it triggers change detection once and then verifies template by calling <em>checkNoChanges</em>. So we could say that <em>tick</em> in development mode executes template twice. Inside <em>tick</em> all component’s hooks are called only after <em>detectChanges</em>, not after <em>checkNoChanges</em>.</p><p>The discussion here is more about how exactly we understand “change detection cycle” term. In my opinion <em>ngDoCheck</em> or <em>tick</em> description should be corrected.</p><h3>Summary</h3><ol><li><em>ngDoCheck</em> is a hook which is called after <em>ngOnInit</em>, <em>ngOnChanges</em> and change detection</li><li><em>ngDoCheck</em> will fire even if your component is <em>OnPush</em>. It’s just a hook, it does nothing until you put something there. Inside <em>ngDoCheck</em> you can run change detection in <em>OnPush</em> component as you wish</li><li><em>ngDoCheck</em> is called twice at the start of the application — once after bootstrapping and second one in zone scheduler</li><li><em>tick</em> function recalculates template 2 times in development mode</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90764a886cba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shake the tree with lightweight tokens]]></title>
            <link>https://medium.com/@daniel.bojarski.db/shake-the-tree-with-lightweight-tokens-9c89fc95d162?source=rss-c5f8a5ab98e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c89fc95d162</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Daniel Bojarski]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 22:33:00 GMT</pubDate>
            <atom:updated>2023-06-13T10:15:37.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8O3mm91xOmNuxsb4LNzkIA.jpeg" /></figure><p>Bundle size is everything that matters. Let’s not waste our time and resources on downloading something that’s not needed. Let’s shake the tree or just let Angular perform the tree shaking process while compiling the code. Tree shaking removes dead code and by dead I mean not only unused code that’s greyed out inside our IDE but also code that was mentioned but wasn’t performed e.g. we imported a module with bunch of components and services but at the end we didn’t use any of those items so why should we add such code to the final bundle size, right? That’s what the tree-shaking in Angular cares for.</p><h3>Ivy compiler</h3><p>Ivy rolled up with Angular 8 with its new way of compiling. Now bundles are smaller and compilation faster. Compiler is now aware of whether we use something or not. We can declare a component and even import it somewhere but if we didn’t use it in a view or as a value inside Injector, it will not be included in our bundle. With the components it’s easy. If we want to use it in a context of some module, we declare it. If we don’t use it, it can be removed. Situation is more complexed with providers.</p><h3>Providers</h3><p>With providers there is a different story. Or actually… No, the story is the same but it is not that obvious whether we use something or not and because of that tree shaking dependencies is much more difficult.</p><p>Let’s look at this example</p><pre>...<br>class MyComponent {<br>  someComponent: SomeComponent;<br>}</pre><p>In this case <strong>SomeComponent</strong> will not be included in our bundle because it is not used. It’s a type declaration and types don’t exist in JavaScript so after transpilation, there will be no such code in JavaScript. We can call it a really low level tree shaking because it is handled by Typescript itself.</p><p>Another example</p><pre>@Component({<br>  ...,<br>  template: &#39;&lt;ng-content&gt;&lt;/ng-content&gt;&#39;<br>})<br>class MyComponent {<br>  @ContentChild(SomeComponent) someComponent: SomeComponent | null;<br>}</pre><p>Now <strong>SomeComponent</strong> will be included in our bundle even if <strong>MyComponent</strong> will not find it inside its view. The real thing that’s happening under the hood is</p><pre>@Component({<br>  ...,<br>  template: &#39;&lt;ng-content&gt;&lt;/ng-content&gt;&#39;<br>})<br>class MyComponent {<br>  @ContentChild(@Inject(SomeComponent)) someComponent: SomeComponent | null;<br>}</pre><p>so <strong>SomeComponent</strong> has been used as a value inside <strong>MyComponent</strong>. Same situation is with injecting providers inside constructor</p><pre>@Component({<br>  ...,<br>  template: &#39;&lt;ng-content&gt;&lt;/ng-content&gt;&#39;<br>})<br>class MyComponent {<br>  constructor(private myService: MyService) {}<br>}</pre><p><strong>MyService</strong> may look like it’s just a type so it shouldn’t be included in bundle but again, in case of providers we’re injecting it so under the hood it will look like this</p><pre>@Component({<br>  ...,<br>  template: &#39;&lt;ng-content&gt;&lt;/ng-content&gt;&#39;<br>})<br>class MyComponent {<br>  constructor(@Inject(MyService) private myService) {}<br>}</pre><p>so again <strong>MyService</strong> has been used as a value and cannot be tree-shaken.</p><h3>providedIn root</h3><p>As we saw providers can’t be tree-shaken because of their injection process which already uses them as a value. Why Angular can’t just check if a dependency imported in a module wasn’t used somewhere and if not then remove it from the bundle? Out of complexity of checking that. I was searching for a response to that question for a long time and:</p><ol><li>Dependencies can be injected in lazy loaded modules</li><li>Dependencies can be injected in dynamically created components so also in directives applied on them or pipes used inside of them</li><li>Dependencies can be used conditionally e.g. used inside conditionally rendered component</li><li>Just injecting something doesn’t mean that we are using it</li></ol><p>So as you can see the answer is — it’s complicated, literally complicated so instead of creating error prone tree shaking mechanism for dependencies Angular depends on tree shaking mechanism from Uglify.js or Webpack which means:</p><ol><li>If you provide something inside a module in providers array, you will get the dependency bundled because of the reference you’ve created and the registry the Injector already did (which means the Injector used the dependency as a value). Well actually passing something to array means using it as a value.</li><li>If you provide something using providedIn: ‘root’ you generally don’t create a reference — there is no import and no usage as a value in any module hence such dependency won’t be bundled until something uses it as a value (injects or returns).</li></ol><p>To make a dependency tree-shakable we have to provide it in a way in which we don’t use them as a value — provide it inside <strong>@Injectable</strong> decorator using <strong>providedIn: ‘root’</strong> key-value.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class MyService {}</pre><p>This way <strong>MyService</strong> is meant to be provided and it will be only if during compilation Angular finds any usage of it.</p><p>Let’s say that we have eager <strong>AppModule</strong>, lazy <strong>MyModule</strong> and <strong>providedIn: ‘root’</strong> <strong>ExtraService</strong>. Inside <strong>MyModule</strong> we have <strong>MyComponent</strong> injecting <strong>ExtraService</strong>. <strong>ExtraService</strong> code will be included only in bundle of <strong>MyModule</strong>.</p><h3>How does Angular create dependencies?</h3><p>At the build stage Angular traverses all files and collects all classes marked as <strong>@Injectable</strong>. It does the same for components, directives, pipes etc. but let’s focus on dependencies.</p><p>If a dependency is used somewhere it will be bundled but what exactly will be bundled? Dependencies are being resolved in runtime. Dependency can be imported even in <strong>AppModule</strong> (root module) but it will not create a instance of it. Instance of a dependency will be created when needed, when injected. It may be created every time in case of providing a dependency in ElementInjector (components for example) or once and then returned every time (singleton dependencies).</p><p>Getting back to the question — what exactly is being bundled? A factory function. When Angular resolves a dependency, it has to know how to resolve it.</p><pre>@Component({<br>  ...,<br>  providers: [MyService]<br>})<br>class MyComponent {<br>  constructor(private myService: MyService) {}<br>}<br><br>@Injectable()<br>export class MyService {<br>  constructor(private myOtherService: MyOtherService) {}<br>}</pre><p>When <strong>MyComponent</strong> is created so is <strong>MyService</strong>. <strong>MyService</strong> has its own dependency called <strong>MyOtherService</strong>. <strong>MyOtherService</strong> might have its own dependencies and so on, so on, so on. When Angular resolves a dependency, it calls the factory function. We can say that by using a dependency we bundle an instruction of how to create instance of it.</p><p>Below you can see the compiled code, a part of chunk of lazy loaded module which has a component injecting <strong>MyService</strong> and <strong>MyService</strong> injects <strong>MyOtherService</strong>.</p><pre>    let MyOtherService = (() =&gt; {<br>      class MyOtherService2 {<br>        constructor() {<br>        }<br>      }<br><br>      return MyOtherService2.\u0275fac = function (t) {<br>        return new (t || MyOtherService2)<br>      }, MyOtherService2.\u0275prov = core.Yz7({<br>        token: MyOtherService2,<br>        factory: MyOtherService2.\u0275fac,<br>        providedIn: &quot;root&quot;<br>      }), MyOtherService2<br>    })(), MyService = (() =&gt; {<br>      class MyService2 {<br>        constructor(myOtherService) {<br>          this.myOtherService = myOtherService<br>        }<br>      }<br><br>      return MyService2.\u0275fac = function (t) {<br>        return new (t || MyService2)(core.LFG(MyOtherService))<br>      }, MyService2.\u0275prov = core.Yz7({<br>        token: MyService2,<br>        factory: MyService2.\u0275fac,<br>        providedIn: &quot;root&quot;<br>      }), MyService2<br>    })()</pre><h3>Lightweight tokens as a rescue for libraries</h3><p>Imagine a library that exports a component with <strong>ng-content</strong>. The component expects that inside the <strong>ng-content</strong> will find another component of a certain type. It will get access to it using <strong>@ContentChild</strong> decorator.</p><pre>@Component({<br>  ...,<br>  template: &#39;{{title}}&#39;<br>})<br>class MyLibCardHeaderComponent {<br>  @Input() title: string;<br>}<br><br>@Component({<br>  ...,<br>  template: `&lt;div class=&quot;card-component&quot;&gt;<br>                &lt;ng-content&gt;&lt;/ng-content&gt;<br>                That&#39;s all folks<br>             &lt;/div&gt;`<br>})<br>class MyLibCardComponent {<br>  @ContentChild(MyLibCardHeaderComponent) cardHeaderComponent: MyLibCardHeaderComponent | null;<br>}</pre><p>We install such library and use it inside our application</p><pre>@Component({<br>  ...,<br>  template: &#39;&lt;my-lib-card&gt;&lt;/my-lib-card&gt;&#39;<br>})<br>class MyComponent {}</pre><p>and we didn’t pass any header to the card (we didn’t insert <em>&lt;my-lib-card-header&gt;</em> inside <em>&lt;my-lib-card&gt;</em>). We could do that, nothing wrong with it, we wanted to display the card without a header. The problem is that inside our library we used <strong>MyLibCardHeaderComponent</strong> as a value which means it will be bundled in the end. Our application bundle will include <strong>MyLibCardHeaderComponent</strong> code when not needed.</p><p>The solution is to use a lightweight token. In our MyLibCardComponent we shouldn’t inject <strong>MyLibCardHeaderComponent</strong> but some token that represents it.</p><pre>const MyLibCardHeaderToken = new InjectionToken(&#39;cardHeaderComponent&#39;);<br><br>@Component({<br>  ...,<br>  template: &#39;{{title}}&#39;,<br>  providers: [{ provide: MyLibCardHeaderToken, useExisting: MyLibCardHeaderComponent }]<br>})<br>class MyLibCardHeaderComponent {<br>  @Input() title: string;<br>}<br><br>@Component({<br>  ...,<br>  template: `&lt;div class=&quot;card-component&quot;&gt;<br>                &lt;ng-content&gt;&lt;/ng-content&gt;<br>                That&#39;s all folks<br>             &lt;/div&gt;`<br>})<br>class MyLibCardComponent {<br>  @ContentChild(MyLibCardHeaderToken) cardHeaderComponent: MyLibCardHeaderComponent | null;<br>}</pre><ol><li>We created an injection token for <strong>MyLibCardHeaderComponent</strong></li><li>We provided created token and mapped it to the decorated component instance</li><li>We search for a token in <strong>@ContentChild</strong> instead of for <strong>MyLibCardHeaderComponent</strong></li></ol><p>This means that in the worst scenario (we won’t place header inside the card) we will include only the <strong>MyLibCardHeaderToken</strong> inside our bundle which is much less code than the header class.</p><h3>There is no tree shaking in library</h3><p>A library cannot be tree shaken. Yes, inside <strong>MyLib</strong> we don’t use <strong>MyLibCardHeaderComponent</strong> now but the purpose of a library is to export components, tools and other things that are suppose to be used elsewhere outside. The tree shaking is performed on the application side which uses the library but to make the tree shaking more effective we have to take care of our code on the library side.</p><h3>To summarize</h3><ol><li>Tree shaking mechanism removes dead code</li><li>Angular is able to remove unused declarations (components, pipes, directives) as they are module-scoped and can be easily detected and removed.</li><li>Tree shaking is complexed in terms of providers due to many conditions they can be used or not</li><li>Angular provides providedIn: ‘root’ @Injectable() setting which tells Angular that such dependency can be provided without creating the reference in a module.</li><li>Angular resolves dependencies at runtime calling a factory function which tells Angular how to create a dependency</li><li>We ought to use lightweight tokens in our libraries to make code more tree-shakable</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c89fc95d162" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[forRoot and forChild in a nutshell]]></title>
            <link>https://medium.com/@daniel.bojarski.db/forroot-and-forchild-in-a-nutshell-ebf860c847e4?source=rss-c5f8a5ab98e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf860c847e4</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Daniel Bojarski]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 15:45:04 GMT</pubDate>
            <atom:updated>2023-06-06T15:48:32.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VixzO6thVNbkdsztqfUcAA.jpeg" /></figure><p>forRoot and forChild are not Angular features at all. It’s just a design pattern, a naming convention that does something but it can be under any name you choose. In case of Angular <strong>RouterModule</strong> it is called <strong>forRoot</strong> and <strong>forChild</strong> so it is recommended to use the same naming convention in our custom modules just for clarification to make it easily understandable what it is going to do but in many cases it does the same, respectively the same…</p><h3>What’s the reason for that?</h3><p>Let’s forget about lazily loaded modules for a moment. Imagine that Angular has just normal modules, all loaded ahead of time. Did you know that all providers provided in any of those modules will end in the root module? Angular during compilation merges providers from all modules and move it to the highest one. It means that <em>AppComponent</em> and <em>ExampleComponent</em> will share the same dependency instance.</p><pre>@NgModule({<br>  imports: [ExampleModule],<br>  providers: [SomeService],<br>  declarations: [AppComponent]<br>  ...<br>})<br>class AppModule {}<br><br>@NgModule({<br>  providers: [SomeService],<br>  declarations: [ExampleComponent]<br>})<br>class ExampleModule {}</pre><p>At the first glance it may appear a little bit weird. We wanted to have a separate instance of <em>SomeService</em> for <em>ExampleModule</em> but we didn’t. It’s how Angular works. If you want to have a separate instance of <em>SomeService</em> for <em>ExampleComponent</em>, provide it in <strong>@Component()</strong> decorator of <em>ExampleComponent</em> to create a local<strong> Injector</strong>.</p><h3>Lazy loaded modules</h3><p>Let’s get back to lazy loaded modules. Lazy means in this case postponed. The module altogether with all its items will be downloaded by the client only when he enters a correct route url under which is the lazy module. This means that it will be after compilation so it is also after dependencies merge process. In such case everything under the <em>LazyModule</em> will have separate dependencies instances (if provided).</p><pre>@NgModule({<br>  providers: [SomeService],<br>  imports: [<br>    RouterModule.forRoot([<br>      { path: &#39;/lazy&#39;, pathMatch: &#39;full&#39;, loadChildren: import(&#39;./lazy-module&#39;).then(m =&gt; m.LazyModule) }<br>    ])<br>  ]<br>})<br>class AppModule {}<br><br>@NgModule({<br>  providers: [SomeService],<br>  imports: [<br>    RouterModule.forChild([<br>      { path: &#39;&#39;, pathMatch: &#39;full&#39;, component: LazyComponent }<br>    ])<br>  ]<br>})<br>class LazyModule {}</pre><p>Two different instances of <em>SomeService</em> for both modules.</p><h3>The purpose of forRoot and forChild</h3><p>Some say that separate <strong>Injector</strong> for lazy module is a opportunity, some say it is a problem. In most cases we load modules lazily for optimization and separate dependencies instances is just a side-effect, unwanted side-effect. What if we would like to share the <em>SomeService</em> across the whole application, to make it a singleton, a single instance for all modules, normal ones and those which are lazy loaded? Well, we can remove <em>SomeService</em> from <em>LazyModule</em>.</p><pre>@NgModule({<br>  providers: [SomeService],<br>  imports: [<br>    RouterModule.forRoot([<br>      { path: &#39;/lazy&#39;, pathMatch: &#39;full&#39;, loadChildren: import(&#39;./lazy-module&#39;).then(m =&gt; m.LazyModule) }<br>    ])<br>  ]<br>})<br>class AppModule {}<br><br>@NgModule({<br>  imports: [<br>    RouterModule.forChild([<br>      { path: &#39;&#39;, pathMatch: &#39;full&#39;, component: LazyComponent }<br>    ])<br>  ]<br>})<br>class LazyModule {}</pre><p>Will it work? Of course it will because even if the module is lazy, it is still a child module of the <em>AppModule</em>. Angular if it can’t find a dependency “here” it will look for it a level higher, and higher, and higher until it meets <strong>NullInjector</strong> which is the highest injector in the app. In this case if we remove <em>SomeService</em> dependency from <em>LazyModule</em> it will find it in <em>AppModule</em> and by so — it will get same instance of the service as the rest of application.</p><p>Problem solved? Well… yes but just for this situation. Now let’s write something that will justify usage of the <strong>forRoot</strong> and <strong>forChild</strong>.</p><h3>Feature module</h3><p>It’s time to create some feature and pack it inside its own module. It will contain a component and a service.</p><pre>@NgModule({<br>  providers: [SquareService],<br>  declarations: [SquareComponent],<br>  exports: [SquareComponent]<br>})<br>class SquareModule {}<br><br>@Injectable()<br>class SquareService {<br>  color = &#39;blue&#39;;<br>}<br><br>@Component({<br>  ...,<br>  template: `<br>    &lt;div style=&quot;width: 10px; height: 10px&quot;<br>         [style.color]=&quot;squareService.color&quot; /&gt;<br>  `<br>})<br>class SquareComponent {<br>  constructor(public squareService: SquareService) {}<br>}</pre><p>Now lets imagine that we want to use that feature in some lazy module and also in the root module e.g. in <em>AppComponent</em>.</p><pre>@NgModule({<br>  imports: [SquareModule, LazyModule],<br>  declarations: [AppComponent]<br>})<br>class AppModule {}<br><br>@NgModule({<br>  imports: [SquareModule],<br>  declarations: [LazyComponent]<br>})<br>class LazyModule {}</pre><p>Now the <em>LazyComponent</em> and <em>AppComponent</em> have different instances of <em>SquareService</em> and we can’t do the same as we did previously to share the instance. Sometimes separate instances are expected but this time we want to have a single <em>SquareService</em> instance across the app to control the square color for all usages of <em>SquareComponent</em>.</p><ol><li>We can’t remove <em>SquareService</em> from <em>SquareModule</em>. It is a feature module which means that it can be in a context without <em>SquareService</em>. Also it may not be used at all, what’s the point in providing <em>SquareService</em> somewhere higher then and increase bundle size?</li><li>We can’t remove <em>SquareService</em> from <em>LazyModule</em> or <em>AppModule</em> because it is not explicitly provided there. They both import the entire <em>SquareModule</em>.</li></ol><p>Let’s rewrite <em>SquareModule</em> a little bit differently by creating <strong>forRoot</strong> method.</p><pre>@NgModule({<br>  declarations: [SquareComponent],<br>  exports: [SquareComponent]<br>})<br>class SquareModule {<br>  static forRoot(): ModuleWithProviders&lt;SquareModule&gt; {<br>    return {<br>        ngModule: SquareModule,<br>        providers: [SquareService]<br>    }<br>  }<br><br>  // forChild is obsolete here. There is nothing more except SquareComponent<br>  // to be imported by child module so declaring such component inside<br>  // NgModule decorator is enough.<br>}</pre><p>Now let’s import such module in both <em>LazyModule</em> and <em>AppModule</em></p><pre>@NgModule({<br>  imports: [SquareModule.forRoot(), LazyModule],<br>  declarations: [AppComponent]<br>})<br>class AppModule {}<br><br>@NgModule({<br>  imports: [SquareModule],<br>  declarations: [LazyComponent]<br>})<br>class LazyModule {}</pre><p>You get it now? Only <em>AppModule</em> imports <em>SquareModule</em> with <em>SquareService</em> provider. <em>LazyModule</em> imports <em>SquareModule</em> just with <em>SquareComponent</em> declaration which means that <em>SquareService</em> will be provided only in the root module — all modules will get the service from there. You also see that <strong>forRoot</strong> and <strong>forChild</strong> which was obsolete here aren’t magical keywords. They can be named as you want, forBanana or forNanana and it’s still gonna work.</p><h3>Let’s configure it a little</h3><p>We can add another static method called for example <em>withConfig</em>. We will modify <em>SquareModule</em> so we will be able to set a default square color in any module that imports <em>SquareModule</em>.</p><pre>const COLOR_TOKEN = new InjectionToken(&#39;color&#39;);<br><br>@NgModule({<br>  declarations: [SquareComponent],<br>  exports: [SquareComponent]<br>})<br>class SquareModule {<br>  static forRoot(): ModuleWithProviders&lt;SquareModule&gt; {<br>    return {<br>        ngModule: SquareModule,<br>        providers: [SquareService]<br>    }<br>  }<br><br>  static withConfig(color: string): ModuleWithProviders&lt;SquareModule&gt; {<br>    return {<br>      ngModule: SquareModule,<br>      providers: [<br>        SquareService,<br>        { provide: COLOR_TOKEN, useValue: color }<br>      ]<br>    }<br>  }<br>}<br><br>// let&#39;s modify the SquareService<br>@Injectable()<br>class SquareService {<br>  color = this.color || &#39;blue&#39;;<br><br>  constructor(@Inject(COLOR_TOKEN) private color: string) {}<br>}</pre><p><em>withConfig</em> has to provide <em>SquareService</em> because if we want to give every module ability to import <em>SquareModule</em> with different behavior of <em>SquareService</em>, we have to give it a separate instance of the service. If <em>withConfig</em> wouldn’t provide <em>SquareService</em>, the service would still be a singleton and <em>COLOR_TOKEN</em> would be the last injected <em>COLOR_TOKEN</em> by some module in order.</p><pre>@NgModule({<br>  imports: [SquareModule.forRoot(), LazyModule],<br>  declarations: [AppComponent]<br>})<br>class AppModule {}<br><br>@NgModule({<br>  imports: [SquareModule.withConfig(color: &#39;red&#39;)],<br>  declarations: [LazyComponent],<br>  exports: [LazyComponent]<br>})<br>class LazyModule {}</pre><p>Now both modules have separate <em>SquareService</em> dependency. Also <em>SquareComponent</em> behaves differently in <em>LazyModule</em> and in <em>AppModule</em>. It is being displayed using yellow color passed with <em>withConfig</em> method and blue color as a default one.</p><h3>RouterModule from inside</h3><p><a href="https://github.com/angular/angular/blob/34989fda7a1d1946f7c9051b364fceafec9c5868/packages/router/src/router_module.ts#L108">Here</a> you can find Angular’s original router definition for <strong>forRoot</strong> and <strong>forChild</strong>. We can see that <strong>forRoot</strong> provides a few dependencies that are common for the whole app and <strong>forChild</strong> just provides given routes.</p><h3>providedIn</h3><p>If you care only about making the service a singleton you don’t have to use the <strong>forRoot</strong> pattern. You can provide the service explicitly from the service file just like that. It will provide the service at the root level.</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>class SquareService {<br>  color = &#39;blue&#39;;<br>}</pre><h3>Summerize</h3><ol><li><strong>forRoot</strong> means “import me only in the root module” and is used to provide some dependencies globally not to double their instances, to make them singletons, to make them shareable across the application</li><li><strong>forChild</strong> means “import me in any module that’s not a root” and exports bare minimum</li><li>You can create any method inside module to make it more configurable</li><li><strong>forRoot</strong> and <strong>forChild</strong> is just a design pattern, not a feature</li><li>Use @Injectable({ providedIn: ‘root’ }) to achieve the same in terms of creating a singleton. Thanks to this notation this service will be <a href="https://angular.io/guide/providers#providedin-and-ngmodules">tree-shakable</a></li></ol><p>Thank guys for reading. This was my first post here so I started lightly. I will post more of it in the near future. Take care, see you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf860c847e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>