<?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 Mike Drakoulelis on Medium]]></title>
        <description><![CDATA[Stories by Mike Drakoulelis on Medium]]></description>
        <link>https://medium.com/@mikedrakoulelis?source=rss-3df7270ac144------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PJRTHR1731kcZxk4sZayQA.png</url>
            <title>Stories by Mike Drakoulelis on Medium</title>
            <link>https://medium.com/@mikedrakoulelis?source=rss-3df7270ac144------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:42:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikedrakoulelis/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[Tidy up your Angular resolvers]]></title>
            <link>https://medium.com/@mikedrakoulelis/tidy-up-your-angular-resolvers-2fece84fb167?source=rss-3df7270ac144------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fece84fb167</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-router]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Mike Drakoulelis]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 13:34:19 GMT</pubDate>
            <atom:updated>2022-12-22T13:34:49.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Enl-bPvtdtHXc0miTAniMQ.png" /><figcaption>The distance between Angular and its Router</figcaption></figure><h4>One of the most useful features of Angular, the Angular resolvers, still has no type support. Can we amend that?</h4><h3>A typical case</h3><p>In Angular, all routes can have preloaded data that will be resolved before the page is rendered. That data can either be static or dynamic and asynchronous. The latter case is achieved via a special type of guard service, the resolvers.</p><p>Here is a typical route definition with two resolvers:</p><pre>class UserResolver implements Resolve&lt;User&gt; {}<br>class ContentResolver implements Resolve&lt;Content&gt; {}<br><br>const routes = [{<br>  path: &#39;my-page&#39;,<br>  component: MyPageComponent,<br>  resolve: {<br>    user: UserResolver,<br>    content: ContentResolver,<br>  }<br>}];</pre><p>The data is then retrievable from within the component by accessing the route data either from the activated route snapshot, or from the activated route in an observable way. E.g. in the component:</p><pre>class MyPageComponent {<br>  <br>  user$: Observable&lt;User&gt;;<br>  content$: Observable&lt;Content&gt;;<br><br>  constructor(private readonly route: ActivatedRoute) {<br>    this.user$ = this.route.data.pipe(map(data =&gt; data.user));<br>    this.content$ = this.route.data.pipe(map(data =&gt; data.content));<br>  }<br>}</pre><p>The data of the route is untyped. It is indeed a difficult task to type it, since there are many parameters to take into consideration, and there seems to be no plans towards it. But! That doesn’t mean we cannot apply our own solution.</p><h3>The proposal</h3><p>My design proposal is inspired by store selectors and promotes resolver reuse given that most times the data property name is the same in all usages.</p><pre>class UserResolver implements Resolve&lt;User&gt; {}<br><br>export const userResolution: ResolveData = { user: UserResolver };<br><br>export const selectRouteUser = (route: ActivatedRoute): Observable&lt;User&gt; =&gt; <br>    route.data.pipe(map(data =&gt; data[&#39;user&#39;]));<br><br>class ContentResolver implements Resolve&lt;Content&gt; {}<br><br>export const contentResolution: ResolveData = { content: ContentResolver };<br><br>export const selectRouteContent = (route: ActivatedRoute): Observable&lt;Content&gt; =&gt;<br>    route.data.pipe(map(data =&gt; data[&#39;content&#39;]));<br><br>// In the routes file<br>const routes = [{<br>  path: &#39;my-page&#39;,<br>  component: MyPageComponent,<br>  resolve: {<br>    ...userResolution,<br>    ...contentResolution,<br>  }<br>}];</pre><p>In the component:</p><pre>class MyPageComponent {<br>  <br>  readonly user$ = selectRouteUser(this.route);<br>  readonly content$ = selectRouteContent(this.route);<br><br>  constructor(private readonly route: ActivatedRoute) {}<br>}</pre><p>Now the type of user$ is inferred to Observable&lt;User&gt;! This also means that there is no need to remember the exact property of the data that matches the user.</p><h3>Avoiding conflicts</h3><p>What if someone accidentally overwrites or wants to overwrite the user key in the resolution? What if there is a conflict with parent route data when the router configuration uses paramsInheritanceStrategy: &#39;always&#39;?</p><p>In my proposal the key is never exposed to the world. All access is being done via the selector. Therefore, we can generate a unique key, and perhaps the best way to do this is by using the JS native Symbol type. Here’s the solution:</p><pre>class UserResolver implements Resolve&lt;User&gt; {}<br><br>const userKey = Symbol(&#39;user&#39;);<br><br>export const userResolution: ResolveData = { [userKey]: UserResolver };<br><br>export const selectRouteUser = (route: ActivatedRoute): Observable&lt;User&gt; =&gt; <br>    route.data.pipe(map(data =&gt; data[userKey]));</pre><h3>Avoiding arguments</h3><p>Using the latest inject() utility function brought by Angular 13, we can also avoid passing the ActivatedRoute in the selector, which results in a cleaner component.</p><pre>export const selectRouteUser = <br>(route: ActivatedRoute = inject(ActivatedRoute)): Observable&lt;User&gt; =&gt; <br>    route.data.pipe(map(data =&gt; data[userKey]));</pre><p>Since the inject() requires that it is run in a constructor or otherwise a provided context, the argument remains as optional and can be passed if the selector needs to be used e.g. in ngOnInit.</p><h3>Final thoughts</h3><p>This proposal came naturally from the need to improve the type support of route data, and link the declarations of resolvers with their usages.</p><p>Currently in Angular there is no easy way to know if and where a resolver is used. Using this solution unused resolvers are easy to spot, and changes in their resolution types are easily reflected in the components and tied to the rest of the Angular language service system. Resulting in… better and more maintainable code!</p><p>Perhaps some day a more compact version of this will be integrated with Angular! Until then, feel free to use it and comment improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fece84fb167" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provide and conquer — Injected angular forms]]></title>
            <link>https://medium.com/@mikedrakoulelis/provide-and-conquer-injected-angular-forms-8688411f425e?source=rss-3df7270ac144------2</link>
            <guid isPermaLink="false">https://medium.com/p/8688411f425e</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Mike Drakoulelis]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 23:33:07 GMT</pubDate>
            <atom:updated>2022-02-01T23:33:07.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Provide-Conquer-Done (Repeat?)" src="https://cdn-images-1.medium.com/max/806/1*gIpZj9WO6dmkECCKX2cdkg.png" /><figcaption>DI(Y) Angular</figcaption></figure><h3>Provide and conquer — Injected angular forms</h3><h4>How can we implement multi-page forms more elegantly?</h4><p>Creating a user-friendly complex form can be hard. Dependency Injection (DI) can also be hard. But put them together, and a solution to a common front-end puzzle appears.</p><p>UX often dictates that complex forms should be broken down to steps, which are spread in multiple pages, and each one is typically validated separately. Sometimes it is also sent to the server for intermediate storage before the final submission. Using Angular, a common approach is to create one form per page, within the container component. The form is validated on submit, before moving to the next step. The form data is either stored in a service, populating the final model, and/or sent to the server. This approach works fine, however it is limited. Navigating between steps might cause inconsistencies as a change in a previous step might have impact on the final model data.</p><h3>Reactive forms to the rescue</h3><p>Angular’s reactive forms have a tree-like structure, which means we can join all step sub-forms under one <em>FormGroup</em>! This way, the validation for the entire form, including the requirement that all steps are complete, can be managed easily.</p><p>Let’s take a look at an example of a 2-step form where the first step registers a user and the second its address.</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br><em>export class </em>UserFormService {<br>  form = <em>this</em>.formBuilder.group({<br>    user: <em>this</em>.formBuilder.group({<br>      username: [&#39;&#39;, Validators.<em>required</em>],<br>      password: [&#39;&#39;, Validators.<em>required</em>],<br>    }),<br>    address: <em>this</em>.formBuilder.group({<br>      city: [&#39;&#39;, Validators.<em>required</em>],<br>      street: [&#39;&#39;],<br>    }),<br>  });<br><br>  <em>constructor</em>(<br>    <em>private readonly </em>formBuilder: FormBuilder,<br>    <em>private readonly </em>http: HttpClient,<br>  ) {<br>  }<br><br>  submitForm(): <em>void </em>{<br>    <em>if </em>(<em>this</em>.form.valid) {<br>      <em>this</em>.http.post(&#39;&#39;, <em>this</em>.form.value);<br>    }<br>  }<br>}</pre><p>Then in the UserComponent:</p><pre>@Component()<br><em>export class </em>UserComponent {<br>  form = <em>this</em>.formService.form.get(&#39;user&#39;);<br><br>  <em>constructor</em>(<em>private readonly </em>formService: UserFormService) {<br>  }<br>}</pre><p>This way at the end of the last step we can validate the entire form model in one go! The page form is decoupled from the component.</p><h3>What about DI though?</h3><p>However, this is far from over. Using the power of Dependency Injection, we can provide each step’s form under a single common token, i.e. PAGE_FORM. The token is injected in each component with a different value. We might even add some form input initialization logic there!</p><pre><em>export const </em>PAGE_FORM = <em>new </em>InjectionToken&lt;FormGroup&gt;(&#39;Page form&#39;);<br><em>export const </em>userFormProvider = {<br>  provide: PAGE_FORM,<br>  deps: [UserFormService, ActivatedRoute],<br>  useFactory: (formService: UserFormService, route: ActivatedRoute) =&gt; {<br>    formService.form.get(&#39;user&#39;).setValue({ username: route.snapshot.queryParams.user, password: &#39;&#39; });<br><br>    <em>return </em>formService.form.get(&#39;user&#39;);<br>  },<br>};</pre><pre>@Component()<br><em>export class </em>UserComponent {<br>  <em>constructor</em>(@INJECT(PAGE_FORM) <em>readonly </em>form: FormGroup) {<br>  }<br>}</pre><h3>That’s great, what else?</h3><p>We now have a way to provide an abstracted version of the form to child components, and avoid passing it through input props. For example, we could create a reusable “Next” button component that is disabled if the form is invalid (UX guidelines aside). This would work even if the button component is used deep in the component tree.</p><pre>@Component({<br>  template: `<br>    &lt;button type=&quot;submit&quot; [disabled]=&quot;form.invalid&quot;&gt;Submit&lt;/button&gt;<br>  `,<br>})<br><em>export class </em>SubmitButtonComponent {<br>  <em>constructor</em>(@Inject(PAGE_FORM) <em>readonly </em>form: FormGroup) {<br>  }<br>}</pre><h3>Conclusion</h3><p>DI is a powerful tool that is often underutilized between Angular devs. This is just an idea of how it can be used to increase reusability. While for most forms this might be an over-engineering, I encourage you to experiment with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8688411f425e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>