Angular Displaying Data

Angular Displaying Data

You can display data by binding controls in an HTML template to properties of an Angular component. In this page, you’ll create a component with a list of heroes. You’ll display the list of hero names and conditionally show a message below the list.

Showing component properties with interpolation

The easiest way to display a component property is to bind the property name through interpolation. With interpolation, you put the property name in the view template, enclosed in double curly braces: {{myHero}}.

 

Follow the setup instructions for creating a new project named displaying-data. Then modify the app.component.ts file by changing the template and the body of the component. When you’re done, it should look like this:

 

src/app/app.component.ts

import { Component } from ‘@angular/core’;

 

@Component({

selector: ‘my-app’,

template: `

<h1>{{title}}</h1>

<h2>My favorite hero is: {{myHero}}</h2>

`

})

export class AppComponent {

title = ‘Tour of Heroes’;

myHero = ‘Windstorm’;

}

 

You added two properties to the formerly empty component: title and myHero. The revised template displays the two component properties using double curly brace interpolation:

 

src/app/app.component.ts (template)

template: `

<h1>{{title}}</h1>

<h2>My favorite hero is: {{myHero}}</h2>

`

The template is a multi-line string within ECMAScript 2015 backticks (`). The backtick (`)—which is not the same character as a single quote (‘)—allows you to compose a string over several lines, which makes the HTML more readable.

Angular automatically pulls the value of the title and myHero properties from the component and inserts those values into the browser. Angular updates the display when these properties change.

Template inline or template file?

You can store your component’s template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator’s templateUrl property.

The choice between inline and separate HTML is a matter of taste, circumstances, and organization policy. Here the app uses inline HTML because the template is small and the demo is simpler without the additional HTML file.

In either style, the template data bindings have the same access to the component’s properties.

IT Professionals, Web Developers, Web Programmers, IT students can Apply for the certification course to move ahead in their careers.

Angular 4 Tutorial IndexBack to Angular 4 Tutorial Main Page

Angular Component Interaction
Angular Data Binding

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?