Marmicode
Blog Post
Younes Jaaidi

A New Syntax for Angular Templates

by Younes Jaaidi • 
Mar 11, 2019 • 4 minutes
A New Syntax for Angular Templates

Angular Templates & Time To First Commit

One of my favorite things about Angular is how .

This is really great; especially if you care about Collective Ownership. With some basic HTML knowledge, anyone can contribute to the application’s development: other teams, external web designers… or even the Product Owner! Why not!?

In other words, using HTML templates which is the average time it takes for someone new in your team to make his first change.

Tired of Importing Modules

Now, the thing that I don’t like that much about Angular is how the template is just a simple HTML file. Wait wait wait! Let me try to explain!

In Angular, every component, directive or pipe has some kind of selector that we can use in our components’ templates. When the template is compiled, the implementation is resolved depending on the component’s module imports.

The official and complete explanation is here:

The problem with this approach is that we every time we want to use another component, a directive or a pipe.

Which Module Should I Import Again?

A while ago, I was explaining reactive forms during a training so I wrote this:

<form [formGroup]="sandwichForm">

it produced the expected error Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’ and I explained that we have to import ReactiveFormsModule, then someone asked:

That’s when I realized that for someone very new to Angular, this was not intuitive at all. That’s also when I noticed that :

Ng VDom

I started thinking about a new way of writing Angular templates so I stumbled upon this brilliant initiative called

export class AppComponent extends Renderable {
  render() {
    return (
      <h1>Hello World!</h1>
    )
  }
}

But still, it was not exactly what I was looking for as I just wanted a new way for writing templates and not a new way of rendering components.

A New Way of Writing Templates

That’s when I got inspiration from which stands for Hyperscript Tagged Markup. I liked how it was simply using standard tagged templates so I came up with the tagged template which works like this:

@Component({
  selector: 'mc-greetings',
  template: `<h1>Hi {{ name }}</h1>`
})
export class Greetings {
  @Input() name: string;
}

@Component({
  selector: 'mc-app',
  template: ngMarkup`
  <${Greetings} name="foo"></${Greetings}>
  <${Greetings} name="john"></${Greetings}>
  `
})
export class AppComponent {}

The working example’s source code is here:

The main advantage of this syntax is that the .

What’s Next?

Surviving AOT

The current implementation doesn’t survive AOT as it would need a pre-compiler or upgrading IVY compiler: ngtsc.

Getting rid of explicit ngModule declarations & exports

As you can see in the given example’s source code, the components, directives, and pipes are still explicitly declared or imported in AppModule.