Angular Templates and Views

1. What is Angular Template and View

A template is an HTML snippet that tells Angular how to render the component in angular application.

The template is immediately associated with a component defines that component’s view.


2. Angular View Hierarchy

The component can also contain a view hierarchy, which have embedded views, defined or associated with other components.

A view hierarchy can include views from components in the same NgModule, but it can also include views from components that are defined in different NgModules.

Key points to consider about view hierarchy are as follows:

  • It is tree of related views that can act as one independent unit.
  • The root view is oftenly called as component’s host view.
  • It plays an important role in Angular change detection.

2.1. View Hierarchy Example

The image below shows the view hierarchy for an application managing super heros and crisis center.

  • The App Component is at the root level and is called as host view containing Heroes and Crisis Center components.
  • The Heroes Component acts as a host view for its child components Hero List and Hero Details which will have their respective views.
  • Likewise Crisis Center Component further hosts two child components containing views for Crisis List and Crisis Details components respectively

Here each component in the hierarchy may have a view associated with it.

3. Types of Templates

There are two ways of defining template in an angular component.

3.1. Inline Template

The inline template is defined by placing the HTML code in back ticks “ and is linked to the component metadata using the template property of @Component decorator e.g.

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

@Component({
  selector: 'app-zipcode',
  template: `
            <p>
            zipcode inline template
            </p>
            `,
  styleUrls: ['./zipcode.component.css']
})

export class ZipcodeComponent implements OnInit {

  constructor() { }

  ngOnInit() { }
}

To define the inline template using @angular/cli, use the command below:

ng generate component zipcode -it

3.2. Template File

The template is defined in a separate HTML file and is linked to the component metadata using the @Component decorator’s templateUrl property e.g.

<p>
  zipcode separate HTML template
</p>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-zipcode',
  templateUrl: './zipcode.component.html',
  styleUrls: ['./zipcode.component.css']
})
export class ZipcodeComponent implements OnInit 
{
  constructor() { }

  ngOnInit() {
  }
}

Happy Learning!!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.