w3resource

Angular - Introduction to Components

A component in Angular controls a patch of the screen called a view. For example, a component can be designed to control various parts of a webpage, such as the header, navigation links, sidebar, content, and footer.

Component Basics

You define a component's application logic-what it does to support the view-inside a class. The class interacts with the view through an API of properties and methods.

For example, the 'HeroListComponent' has a 'heroes' property that holds an array of heroes. Its selectHero() method sets a selectedHero property when the user clicks to choose a hero from that list. The component acquires the heroes from a service, which is a TypeScript parameter property on the constructor. The service is provided to the component through the dependency injection system.

Example Component Class

TypeScript Code:

export class HeroListComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private service: HeroService) { }

  ngOnInit() {
    this.heroes = this.service.getHeroes();
  }

  selectHero(hero: Hero) { this.selectedHero = hero; }
}

Angular creates, updates, and destroys components as the user navigates through the application. Your app can take action at each moment in this lifecycle through optional lifecycle hooks like ngOnInit().

Component Metadata

In Angular, the @Component decorator identifies the class immediately below it as a component class and specifies its metadata. In the example code below, you can see that 'HeroListComponent' is just a class with no special Angular notation or syntax at all. It's not a component until you mark it as one with the @Component decorator.

The metadata for a component tells Angular where to get the major building blocks it needs to create and present the component and its view. It associates a template with the component either directly with inline code or by reference. Together, the component and its template describe a view. The metadata also configures how the component can be referenced in HTML and what services it requires.

Example Component Metadata

TypeScript Code:

@Component({
  selector: 'app-hero-list',
  templateUrl: './hero-list.component.html',
  providers: [HeroService]
})
export class HeroListComponent implements OnInit {
  /* . . . */
}

This example shows some of the most useful @Component configuration options:

In Angular, before a view is displayed, the directives and the binding syntax in the template are evaluated and the HTML and DOM modified according to the program data and logic.

selector: A CSS selector that tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML. For example, if an app's HTML contains <app-hero-list></app-hero-list>, then Angular inserts an instance of the HeroListComponent view between those tags.

templateUrl: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the template property. This template defines the component's host view.

providers: An array of providers for services that the component requires. In the example, this tells Angular how to provide the "HeroService" instance that the component's constructor uses to get the list of heroes to display.

Templates and Views

A component's view is defined by its companion template. A template is a form of HTML that tells Angular how to render the component.

Views are typically arranged hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's host view. The component can also define a view hierarchy that contains embedded views hosted by other components.

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

Template syntax

A template looks like regular HTML, except that it also contains Angular template syntax, which alters the HTML based on your app's logic and the state of app and DOM data. Your template can use data binding to coordinate the app and DOM data, pipes to transform data before it is displayed, and directives to apply app logic to what gets displayed.

For example, here is a template for the Tutorial's 'HeroListComponent'.

Example Template

HTML Code:

<h2>Hero List</h2>
<p><i>Pick a hero from the list</i></p>
<ul>
  <li *ngFor="let hero of heroes" (click)="selectHero(hero)">
    {{hero.name}}
  </li>
</ul>
<app-hero-detail *ngIf="selectedHero" [hero]="selectedHero"></app-hero-detail>

Live Demo

See the Pen angular-HeroListComponent by w3resource (@w3resource) on CodePen.


This template uses typical HTML elements like <h2> and <p> and also includes Angular template-syntax elements such as *ngFor, {{hero.name}}, (click), and [hero]. These elements tell Angular how to render the HTML to the screen using program logic and data.

  • The *ngFor directive tells Angular to iterate over a list.
  • {{hero.name}}, (click), and [hero] bind program data to and from the DOM, responding to user input.
  • The <app-hero-detail> tag in the example is an element that represents a new component, HeroDetailComponent. HeroDetailComponent (though not shown in the code snippet) defines the hero-detail child view of HeroListComponent. Observe how custom components like this mix seamlessly with native HTML in the same layouts.

Data Binding

Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses into actions and value updates. Writing such push and pull logic by hand is tedious, error-prone, and a nightmare to read.

Angular supports two-way data binding, a mechanism for coordinating the parts of a template with the parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides.

This example from the "HeroListComponent" template uses three of these forms.

Example Data Binding

HTML Code:

<li>{{hero.name}}</li>
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
<li (click)="selectHero(hero)"></li>

Live Demo:

See the Pen angular-HeroListComponent by w3resource (@w3resource) on CodePen.


  • The {{hero.name}} interpolation displays the component's hero.name property value within the <li> element.
  • The [hero] property binding passes the value of selectedHero from the parent HeroListComponent to the hero property of the child HeroDetailComponent.
  • The (click) event binding calls the component's selectHero method when the user clicks a hero's name

Two-way data binding (used mainly in template-driven forms) combines property and event binding in a single notation. Here's an example from the HeroDetailComponent template that uses two-way data binding with the ngModel directive:

<input [(ngModel)]="hero.name">

In two-way binding, a data property value flows to the input box from the component, as with property binding. The user's changes also flow back to the component, resetting the property to the latest value as with event binding.

Angular processes all data bindings once for each JavaScript event cycle from the root of the application component tree through all child components.

Data binding plays an important role in communication between a template and its component and is also important for communication between parent and child components.

Pipes

Angular pipes let you declare display-value transformations in your template HTML. A class with the @Pipe decorator defines a function that transforms input values to output values for display in a view.

Angular defines various pipes, such as the date pipe and currency pipe. You can also define your own custom pipe.

To specify a value transformation in an HTML template, use the pipe operator (|).

'{{interpolated_value | pipe_name}}'

You can chain pipes, sending the output of one pipe function to be transformed by another pipe function. A pipe can also take arguments that control how it performs its transformation. For example, you can pass the desired format to the date pipe.

HTML Code:

<p>Today is {{today | date}}</p>
<p>The date is {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'shortTime'}}</p>

Live Demo:

See the Pen angular-selectedHero by w3resource (@w3resource) on CodePen.


Directives

Angular templates are dynamic. When Angular renders them, it transforms the DOM according to the instructions given by directives. A directive is a class with a @Directive() decorator.

A component is technically a directive. However, components are so distinctive and central to Angular applications that Angular defines the @Component() decorator, which extends the @Directive() decorator with template-oriented features.

In addition to components, there are two other kinds of directives: structural and attribute. Angular defines a number of directives of both kinds, and you can define your own using the @Directive() decorator.

Just as for components, the metadata for a directive associates the decorated class with a selector element that you use to insert it into HTML. In templates, directives typically appear within an element tag as attributes, either by name or as the target of an assignment or a binding.

Structural Directives

Structural directives alter the layout by adding, removing, and replacing elements in the DOM. The example template uses two built-in structural directives to add application logic to how the view is rendered.

HTML Code:

<li *ngFor="let hero of heroes"></li>
<app-hero-detail *ngIf="selectedHero"></app-hero-detail>

Live Demo:

See the Pen angular-date-pipe by w3resource (@w3resource) on CodePen.


  • *ngFor is an iterative directive; it tells Angular to stamp out one <li> per hero in the heroes list.
  • *ngIf is a conditional directive; it includes the HeroDetail component only if a selected hero exists.

Attribute Directives

Attribute directives alter the appearance or behavior of an existing element. In templates, they look like regular HTML attributes, hence the name.

The ngModel directive, which implements two-way data binding, is an example of an attribute directive. ngModel modifies the behavior of an existing element (typically <input>) by setting its display value property and responding to change events.

<input [(ngModel)]="hero.name">

Angular has more pre-defined directives that either alter the layout structure (for example, ngSwitch) or modify aspects of DOM elements and components (for example, ngStyle and ngClass).

Summary

Understanding components is fundamental to developing Angular applications. By leveraging components, templates, data binding, pipes, and directives, you can create dynamic, responsive, and maintainable applications. Components allow you to break down your application into smaller, reusable pieces, making development more efficient and code easier to manage.

Previous: Introduction to services and dependency injection
Next: User Input



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/angular/introduction-to-components.php