left-icon

Angular 2 Succinctly®
by Joseph D. Booth

Previous
Chapter

of
A
A
A

CHAPTER 9

Components

Components


Now that the environment is up and running and we’ve seen some of the tools we can use, it is time to dig into the actual features and language syntax of Angular 2. We will start with the most basic element: the component.

The component is an encapsulated piece of code that is generally responsible for handling a piece of the user’s screen. We define our base page with a collection of CSS selectable elements and then ask Angular to call the proper component to populate the selected element. As the user navigates through our site, Angular creates the components necessary to populate the page elements.

Component files

Each component should reside in its own .ts file. This file will typically contain three sections: the import section, which specifies the other components we want to use (import) in our component; the metadata section, which provides details about the component to Angular; and finally, the actual component code itself.

Import

The basic syntax is:

Code Listing 46

import { Component_name } from 'module location'

At minimum, you will need to import Component from the Angular core. This is necessary to provide metadata about the component to Angular.

Tip: When adding the import to your code, specify the from name first; this will allow Visual Studio Code to use IntelliSense to validate the component name automatically.

Code Listing 47

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

There are many components available in the Angular libraries. Some of the possible component classes you are likely to need are:

  • Http in @angular/http: Basic HTTP operations like GET, POST, etc.
  • Router in @angular/router: Maps URLs to components.
  • Location in @angular/common: Allows interaction with the browser’s URL.

As you start working with Angular 2, you will explore the various libraries available both in the base libraries provided by Angular and possibly any third-party libraries that provide components to help your front-end web development work.

Metadata

The metadata is a set of properties that describe the component to Angular. There several options available, but the most commonly used are the selector property and the template property. For components, the selector and a template method are both required.

selector

The selector value is a string that refers to the element on the page where the component should render its content. The selector typically is an element name, such as <main-app>. Other options include:

  • Class: <div class="main-app"> </div>

Selector: .main-app

  • Attribute: <div data-name="main-app"> </div>

Selector: [data-name]

template

The template is the HTML code that will be inserted into the selected element when the component is rendered. The template can be simply HTML code, but it is much more powerful than that. For example, any values enclosed in double braces {{  }} will get replaced with a value from the component class. Consider the following template code.

Code Listing 48

<h1>Company: {{CompanyName}} </h1>

This code would have the {{CompanyName}} replaced with the value of the CompanyName property in the component’s class code. This process is referred to as interpolation, and is just the tip of the iceberg of template capabilities.

In the next chapter, we will explore the template capabilities in more detail.

templateUrl

If the template code is too large, or you just want to separate the HTML view from the component, you can use the templateUrl instead of the template, and provide a file location where the template content can be found.

Note: You can only have one or the other (template or templateUrl).

styles

The styles attribute allows you to define styles for elements within the template. The element is a collection of styles (delimited by brackets [ ]). Within the collection, you can add classes and styles to be used by your component. For example, the following styles will set the <p> tags within your component to an antique white background and the <h1> tags to a navy blue text color.

Code Listing 49

[ `

   p: { background-color: antiquewhite; }

    h1: { color: navy; }

` ]

Notice the use of the backtick ( ` ) character to create multiline styles.

styleUrls

Similar to the templateUrl property, the styleUrls property can be used to specify the styles via a style sheet (or collection of style sheets). The following syntax shows a sample property value that will load both the style.css and customer.css files.

Code Listing 50

styleUrls: [ 'app/styles.css','app/customer/css' ]

In this case, the style sheets are found in the app folder. The URL is relative to the application root (typically where the index.html file resides).

encapsulation

The encapsulation attribute is a feature that allows Angular 2 to work with old browsers (those which don’t support the Shadow DOM). There are three possible values in the enumeration:

  • Emulated
  • Native
  • None

The default value, Emulated, creates a surrogate ID for the host selector and pre-processes the styles to include this ID. This allows older browsers to have CSS unique to the component.

Native (for new browsers) takes advantage of the Shadow DOM and creates a Shadow Root for the component. This is the preferred approach to keep your component styles isolated if you know your target browsers are new, and you don’t need to support older browsers.

None doesn’t do anything, but leaves the styles as they are in the DOM.

To include the enumeration, you need to import the ViewEncapsulation enum values from the angular/core library, as shown in Code Listing 51.

Code Listing 51

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

These are the basic component properties to get started, but there are few more that we will cover in later chapters.

Class code

The actual code that makes up the component is the final piece of the component. We use the export class statement to define the name of the class and its content. Here is an example class in the AppComponent.

Code Listing 52

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

@Component({

  selector: 'main-app',

  template: `<h1>{{ClubTitle}}</h1>

             <h2>{{LeagueTitle}} </h2> `

})

export class AppComponent {

  // Properties

  ClubTitle: string

  LeagueTitle: string;

  // Constructor 

  public constructor()  {

    this.ClubTitle ="The 422 Sportsplex";

    this.LeagueTitle="Adult Over 30 Leagues";

   }

  // Class methods

  public ChangeLeagues( newLeague: string) {

      this.LeagueTitle = newLeague;

   }

}

The properties are TypeScript variables that we plan to use in the class. In this example, we are simply defining two strings to hold the club and league title. The constructor is the code that gets invoked when the component is first instantiated. You can only have one constructor in your component.

You can also create class methods, such as the ChangeLeagues() method. This method simply changes the LeagueTitle property, which will then be updated in the template display.

The component class code is based on TypeScript classes, and allows you to create properties and define their scope, as well as create class methods. By default, all properties and methods in the class are considered public.

Tip: In my opinion, explicitly using the public keyword is good programming style.

Properties

To define properties within the class, you just need to declare the variable, and optionally, provide it with a data type. The basic syntax is:

Code Listing 53

[ public | private | protected ]

 Property Name: data Type

[ = initial Value ]

By default, the property is public, meaning its value can be seen outside the class. Private means the variable is only used within the class, and it will not be defined if you try to access it externally. Protected means it acts like private, except that derived classes can use the property as well.

Property Name follows general rules for defining a variable: it can contain alphanumeric values and an underscore character. It cannot begin with a number.

data Type indicates the kind of data you expect to put in a property. It is technically optional, since TypeScript can infer data type by its usage, but it is a good habit to specify the type. Valid data types include:

  • number
  • string
  • boolean

You can also assign an initial value as part of the declaration by adding an equal sign and the initial value (that matches the property’s data type). You can declare the initial value by referencing another property with the class (including ones defined later in the class). To reference a class property, you will need to qualify the variable name with the this prefix.

You can also use null and undefined for initial values when declaring properties. These behave the same way they do in JavaScript.

Here are some example property definitions, showing the various features you can use when creating properties in the class code.

Code Listing 54

  private LastClub: string = this.PriorOwner;

  protected _PriorOwner: string = "YSC Sports";

  private CallCtr: number =0;

  private IsAdmin: boolean = false;

  ClubTitle: string = this._PriorOwner;

  LeagueTitle: string;

  private _CurrentOwner: string;

You can initialize the properties in-line or later in a class method, such as the constructor.

Accessors

Sometimes, providing direct access to a property can be risky, so you might want to control the access to the variable through program code. This is done by creating accessor functions that act just like properties, but call a function to get or set the property values behind the scenes.

To create an accessor function, you need to declare the keyword GET or SET, a function name, and a data type. The syntax is shown in Code Listing 55.

Code Listing 55

get| set    function_name() :  Data Type

Get accessor

The GET function is used to return the value of the “property.” It could simply be a private field in the class, or a more complex business rule. For example, if we want our ClubOwner property to return the current owner of the club, the function would look like this.

Code Listing 56

  get ClubOwner() : string

  {

      return this._CurrentOwner;

  }

In this example, the private function ClubOwner simply returns the value of the private variable _CurrentOwner.

Set accessor

The set accessor function is used to update the property, and can be omitted to create a read-only property. You can add business logic to accept or deny the update, or you might need to do additional work when the property is updated. Here is an example of a SET function that does two tasks. First, it confirms that you have admin permission to make the update, and second, it puts the original owner value into the _PriorOwner private variable.

Code Listing 57

  set ClubOwner(newOwner: string) {

    // Check permissions

    if (this.isAdmin) {

        this._PriorOwner = this._CurrentOwner;

        this._CurrentOwner = newOwner;

      }

  }

Assuming you’ve retrieved the isAdmin flag from some database call, you could easily control who has access to various properties in the class.

Constructors

The constructor is a public method (it cannot be private or protected) that is called whenever the class is instantiated. If you don’t specify a constructor method, a default constructor is used. A class can only have one constructor.

The syntax is just like any void TypeScript function, using the name constructor. It is often used to initialize variables, or perhaps make a database call to set various properties of the object.

Code Listing 58

  // Constructor 

  public constructor() {

    this.ClubTitle ="The 422 Sportsplex";

    this.LeagueTitle="Adult Over 30 Leagues";

    this.SeasonStart = new Date();

  };

Class methods

A class method is a TypeScript function, and can be public, private, or protected, just like the properties. The syntax for declaring the method is:

Code Listing 59

[ public | private | protected ]

   Method Name ( optional parameters )

 : optional return type

{     body of method

}

public is the default, and if no return type is specified, it will be undefined. For example, in our example, the following method could be used to change the current league being displayed.

Code Listing 60

  // Class methods

   public ChangeLeagues( newLeague: string) {

      this.LeagueTitle = newLeague;

      // Retrieve league details

   }

Remember that any class properties need to use the qualifier this. You can create variables internally in the method, scoped to adjust the method as needed.

Summary

Once you’ve provided the module with info about how it will be used within your application (the CSS selector and template), you can work with the TypeScript language to provide whatever business logic your application needs. As your logic updates properties in the class, those updates will appear on the page via the data-binding (interpolation) system built into Angular. We’ll explore this more in the next chapter.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.