Angular 2 — Template Syntax

One of the nice features with Angular 2 is the ability to use <template> tags to work with built in directives like ngIf and ngFor.

Both ngIf and ngFor manipulates element subtrees on the DOM. These directives used properly can result in increased performance by freeing up resources on the DOM.

Angular 2 expands the HTML *asterisk syntax into <template> syntax in the background anyway, but i’ve found doing it this way is cleaner to read. There’s also (for the time being?) a clashing issue when you try to apply an ngIf and ngFor to the same element with the *asterisk syntax, structuring your template logic using <template> tags gets around this issue.

When using ngIf and ngFor with <template> tags, remember to wrap these attributes in square brackets. We can ignore the *asterisk prefix that’s required when using them directly on the HTML elements.