Angular 2 - Templates


Advertisements

In the chapter on Components, we have already seen an example of the following template.

template: '
   <div>
      <h1>{{appTitle}}</h1>
      <div>To Tutorials Point</div>
   </div>
'

This is known as an inline template. There are other ways to define a template and that can be done via the templateURL command. The simplest way to use this in the component is as follows.

Syntax

templateURL:
viewname.component.html

Parameters

  • viewname − This is the name of the app component module.

After the viewname, the component needs to be added to the file name.

Following are the steps to define an inline template.

Step 1 − Create a file called app.component.html. This will contain the html code for the view.

App Component

Step 2 − Add the following code in the above created file.

<div>{{appTitle}} Tutorialspoint </div>

This defines a simple div tag and references the appTitle property from the app.component class.

Step 3 − In the app.component.ts file, add the following code.

import { Component } from '@angular/core';

@Component ({
   selector: 'my-app',
   templateUrl: 'app/app.component.html'  
})

export class AppComponent {
   appTitle: string = 'Welcome';
}

From the above code, the only change that can be noted is from the templateURL, which gives the link to the app.component.html file which is located in the app folder.

Step 4 − Run the code in the browser, you will get the following output.

Run the code

From the output, it can be seen that the template file (app.component.html) file is being called accordingly.

Useful Video Courses


Video

AngularJS Online Training

16 Lectures 1.5 hours

Anadi Sharma

Video

Angular 2 Online Training

28 Lectures 2.5 hours

Anadi Sharma

Video

Step By Step Angular For Beginnners

11 Lectures 7.5 hours

SHIVPRASAD KOIRALA

Video

Ionic & Angular JS: Principles Of Mobile and Web Development

16 Lectures 2.5 hours

Frahaan Hussain

Video

Angular 8 Full Stack Development With Spring Boot

Best Seller

69 Lectures 5 hours

Senol Atac

Video

JWT Role Based Authorization With Spring Boot And Angular 8

53 Lectures 3.5 hours

Senol Atac

Advertisements