9.2 KiB
Angular Templating
Article Overview
ADD MORE FLAVOR TEXT TO START THIS FLIPPIN' SWEET ARTICLE OFF
Templates allow developers to create embedded views of UI from another location. These templates are able to be passed and handled much like most values in JavaScript. You're also able to leverage a set of APIs built into these templates to pass and manipulate data from one template to another during the render process. The ability to have this tool at your disposal not only makes Angular very appealing as a component framework, but is how many of it's internal processes are built.
While this article is far from a comprehensive list of all template related APIs, there are three primary APIs that are used within a user defined template that I want to touch on in this article:
ng-templateng-container- Structural Directives (such as
*ngIf)
A Brief Introduction to Templates
Introductory Example
Before we dive into the meat of this article, let's do a quick recap of what a templates look like. While Angular templates come in many shapes and sizes, a straightforward example of what one in action might look might be something similar to this:
<ng-template #templHere>
<p>False</p>
</ng-template>
<p *ngIf="bool; else templHere">True</p>
In this example, we are creating a template and assigning it to a template variable. This template variable will make templHere a valid variable whereever it's referenced within the template (much like how variables are bound from the component logic to the template, you can bind data from within the template to other parts of the template).
###FACTCHECK:
These template variables can then be referenced by siblings or children, but not by cousin elements
We are then creating a structural directive ngIf that checks if bool is true or false. If it is false, it will then check if the else condition has a value assigned to it. In this example, it does: The template we've assigned to templHere. Because there's a value there, when bool is false, <p>False</p> will be rendered, but if bool is true, <p>True</p> will be rendered. If you had forgotten to include the ngIf, it would never render the False element because the ng-template component never renders to the DOM unless otherwise specified
Example Alternative - Let's Checkout ngTemplateOutlet
But there's a simpler much more complex another way show the same template code above!
<ng-template #templHere>
<p>False</p>
</ng-template>
<ng-template #ngIfTrueCondTempl>
<p>True</p>
</ng-template>
<ng-template [ngTemplateOutlet]="bool ? ngIfTrueCondTempl : templHere"></ng-template>
While this is not how the ngIf structural template works internally (we'll touch on that in a bit, including taking a look at how Angular's source code is written), this is a good introduction to the ngTemplateOutlet input to the ng-template component.
While I'd mentioned previously that ng-template does not render to the DOM, because we're using ngTemplateOutlet, it will create an embedded view based on the template passed into it. This embedded view will be located in the DOM where the ng-template that used the ngTemplateOutlet directive. Knowing that, you can see that the following example would show the user three of the most mythical beasts imaginable:
<ng-template #templateName><button>🦄🦄🦄</button></ng-template>
<ng-template [ngTemplateOutlet]="templateName"></ng-template>
Once you understand that, combined with knowing about template variables (which we covered at the beggining of this section), it can be easier to understand that we're just doing a turnary to pass the correct template based on the value of bool to create an embedded view of that template.
Pass Data To Templates - The Template Context
You know how I mentioned that you can pass data between templates (at the start of the article)? That is built on top of the concept of Contexts. Context are a way of passing data just like you would parameters to a function by creating template variables for the template that is created with a context.
That said, they don't rely on the order of parameters (they rather rely on the name of the parameters to pass to the template) and are all entirely optional whether they are consumed by the template or not. In this way, they more similar to ADDLINK:namedFunctions from Python 3 than they are arguments in a JavaScript function
So, now that we know what they are in broad terms, what do they look like?
Passing Context To Rendering
While we used the ngTemplateOutlet directive before to render a template, we can also pass an input to the directive ngTemplateOutletContext in order to pass a context. A context is just an object with a standard key/value pairing.
<ng-template [ngTemplateOutlet]="templateName"
[ngTemplateOutletContext]="{$implicit: 'Hello World', personName: 'Corbin'}">
</ng-template>
From there, you can use let declarations to create template variables in that template based on the values passed by the context like so:
<ng-template #templateName let-implicitTemplVal let-boundPersonTemplVar="personName">
<p>{{implicitTemplVal}} {{boundPersonTemplVar}}</p>
</ng-template>
Here, you can see that let-templateVariableName="contextKeyName" is the syntax to bind any named context key's value to the template variable with the name you provided after let. There is an edge-case you've probable noticed though, the $implicit key of the context is treated as a default of sorts, allowing a user to simply leave let-templateVariableName to be the value of the $implicit key of the context value.
Notes
As a qiuck note, I only named these template variables differently from the context value key in order to make it clear that you may do so. let-personName="personName" is not only valid, but can be clearer to other developers of it's intentions in the code.
It's also important to note that a template variable is bound to the element and it's children. Attempting to accessing the template variable from a sibling, parent, or cousin's template code is not valid. To recap:
<!-- ✅ This is perfectly fine -->
<ng-template #templateOne let-varName><p>{{varName}}</p></ng-template>
<!-- ❌ This will throw errors, as the template variable is not set in siblings -->
<ng-template #templateTwo let-thisVar></ng-template>
<p>{{thisVar}}</p>
ViewChild
###FACTCHECK: Okay, that's neato - but what if I DID want to pass it to cousins? After all, just like we don't want christmas trees in our callback chains, we sure don't want super deeply nested templates if we can avoid it.
Well, there's actually a way to get a reference to the template from the component logic rather than the template:
@Component({
selector: 'app',
template: `
<div>
<ng-template #templName>Hello</ng-template>
</div>
<ng-template [ngTemplateOutlet]="templName"></ng-template>
`
})
export class AppComponent implements OnInit {
}
@ViewChild('templateName', {read: TemplateRef<any>})
Embedded Views - We Get It You Like The Expression
It might seem like I've been trying to use embedded view far too much, possibly avoiding using render more than might seem logical at first, but there's a reason for this:
Angular tracks them seperately from other components.
Angular also allows you find, reference, modify, and create them yourself! 🤯
Structural Directives - What Sorcery is this?
A structural directive is something like *ngFor or *ngIf, they allow you to turn whatever you're looking at into a template.
EG:
<div *ngIf="bool">
<p>Hello</p>
</div>
Might turn into something like*:
<ng-template #abcd>
<div><p>Hello</p></div>
</ng-template>
<ng-template [ngTemplateOutlet]="bool ? abcd : null"></ng-template>
Internally.
* This is guestimation, don't attack if not perfectly correct
- Internally.
So when you mark something with a structural directive, you're turning it into an Angular template and then passing that element as a child to that template.
You can also take the template variables and turn them into a way to communicate with the structural directive, like how *ngFor works:
https://angular.io/guide/structural-directives#microsyntax
For more information on this see:
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
MOVEME: EXPLAINBTR: Template Variables
Template variables can reference other types other than templateRef (just like {read} can be used with ViewChild) by using the prop input equality operator like values are passed to inputs (#templArg="exportAsName") that matches the exportAs value of the component/directive you're trying to "spy" on