Internal and external templates

As our applications grow in size and complexity, chances are that our templates will grow as well, hosting other components and bigger chunks of HTML code. Embedding all this code in our component class definitions will become a cumbersome and unpleasant task and it will also be quite prone to errors. In order to prevent this from happening, we can leverage the templateUrl property, pointing to a standalone HTML file that contains our component HTML markup.

Back to our previous example, we can refactor the @Component decorator of our TimerComponent class to point to an external HTML file containing our template. Create a new file named timer.component.html in the workspace where our timer.component.ts file lives and populate it with the same HTML we configured in our TimerComponent class:

<div class="container text-center">
<countdown [seconds]="25"
(complete)="onCountdownCompleted()"
#counter >
</countdown>
<p>
<button class="btn btn-default"
(click)="counter.seconds = 25">
Reset countdown to 25 seconds
</button>
</p>
<p *ngIf="counter.seconds < 10">
Beware only !
<strong>{{ seconds }} seconds</strong> left
</p>
</div>

Now, we can polish our @Component decorator to point to that file instead of defining the HTML inside the decorator metadata:

@Component({
selector: 'timer',
templateUrl: './timer.component.html'
})
export class TimerComponent {
// Class follows below
}

External templates follow a certain convention in Angular, enforced by the most popular Angular coding style guide out there, which is to share the same filename as the component they belong to, including any filename prefix or suffix we might append to the component filename. We will see this when exploring component naming conventions in Chapter 6, Building an Application with Angular Components. This way, it is easier to recognize, or even search with your IDE's search built-in fuzzy finder tool, which HTML file is in fact the template of a specific component.

What is the threshold for creating standalone templates rather than keeping the template markup inside the component? It depends on the complexity and size of the template. Common sense will be your best advisor in this case.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset