This is a follow-up, to “Angular: Why you should consider using template outlet instead of content projection”, showing how to implement tabs in Angular using NgTemplateOutlet to avoid potential performance issues of using ng-content described in aforementioned text.

This article is written for Angular 2.x Update: Angular 4 deprecates <template> in favor to <ng-template> and introduces new set of features which may be superior to method presented in this article.

final result

App’s main component

We’ll start with the main application component to illustrate tabs’ API.

Tabs feature will consist of two components:

app-tabs which renders tabs according to information provided by its children.

which renders tabs according to information provided by its children. app-tab holding information about the tab — name and reference to specific template.

Using two components will make code more maintainable and template look clean.

<template> elements serve purpose of holding content to display when specific tab is active by using its TemplateRef .

Tab component

TabComponent holds bound information which is read by TabsComponent .

Input decorator allows us to bind values. In this case: name string and templateRef .

Tabs component

First, we want to access its children (outside the template) by using ContentChildren decorator which returns QueryList object containing what we want.

Children are available when ngAfterContentInit hook is executed. currentTab property will hold the reference to the current tab. First tab will be referred by default.

Next, we want the component to render tabs and content with example styling.

We’re rendering span element for each tab and ngTemplateOutlet directive accepts current tab’s TemplateRef so appropriate content will be rendered.

Now, we need to add some interactivity to make tabs useful.

TabsComponent has two new methods used by template:

isSelected which will tell if provided tab is selected. Used with ngClass directive to add selected class to appropriate tab.

which will tell if provided tab is selected. Used with directive to add class to appropriate tab. onTabClick which is bound to click event accepting reference to clicked tab and setting it as current.

That’s it!

You can see the final result by checking this plunker here.

Click or tap ❤ if you found this article useful. You’ll make it visible to wider audience. Thanks!