Angular Components & Modules

angular componentsa nd modules

This article on Angular components is part of the Learning Angular series.

Components form the building blocks of the framework and is defined using the @Component decorator. The decorator takes in the selector, template, styles and other properties which specify the metadata require to process the component.

Default Angular Component – AppComponent

When we create an Angular application for the first time using the ng new project-name command, the created project by default contains one component named the AppComponent (app.component.ts) file. If we look closely, one can see the following files in the src/app folder

All the 4 files pertain to the AppComponent, which is the default component created when an Angular application is created with ng new my-app command

Understanding the Component

By default, app.component.ts (AppComponent), is the bootstrapped component in the AppModule. Which means that it will be loaded by default by Angular, as discussed in the earlier post Introduction to Angular

Opening up the app.component.ts, you will find the following piece of code:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'learning-angular';
}

@Component is the decorator that makes Angular (TypeScript) understand that this is a component, and to do the required tasks when this class in initialized.

If you see the Component decorator takes a few paramters (called metadata), namely selector, templateUrl, styleUrls, etc. The others will be taken up as and when required.

Let’s take a look at them individually:

selector

This will form the tags that will make thse components usable in the HTML file. In the app.component.ts, we can find

selector: 'app-root'

And now, if we open the the index.html, we can find the following code:

<body>
  <app-root></app-root>
</body>

So this makes sure that the app.component.ts is loaded in the index.html by default and all the rest of the components that we might need to create in the future load up from there. Every individual component we will create will have a selector tag, so that we can add them up in the HTML.

The selector needs to be unique in the project.

templateUrl

Provides the path for the HTML to load for the current component. In the default AppCOmponent, the tempateUrl is set to ./app.component.html which resides in the same folder.

templateUrl: './app.component.html',

We can also use inline templating in the TypeScript file by using the template metadata.

template: '<h1>Custom Tags are allowed</h1>'

For multiline, we can use backticks to wrap the html

template: `<div id="wrapper">
  <h1>Custom tags are allowed</h1>
</div>`

styleUrls

The styleUrls metadata uses the same approach as that of the templateUrl metadata, the only difference being, it takes an array of paths to stylesheet files to be used for rendering the component.

styleUrls: ['./app.component.scss', './xyz.scss']

We can also use inline styling in the AppComponent file, using the styles metadata

styles: [
    h3 {
        color: blue;
    }
]

Creating a new angular component

A new component can be created manually or by using the Angular CLI

Creating manually

While the components can be created anywhere inside src/app folder, it’s preferable to keep the all the files related to the component in a similarly named folder.

Lets created a component name FirstComponent.

  1. Inside src/app folder, create another folder, conventionally the name of the component, named first
  2. Create a new file inside the folder named first.component.ts
  3. Create a new file in the same folder named first.component.html
  4. Add the following lines to the first.component.ts file:
// import the component module
import { Component } from '@angular/core';
// Define the selectors, so Angular knows what to do with this class
@Component({
    // Required parameters
    // The selector should not clash with any other selectors
    selector: 'first-component',
    // selector: '[first-component]'
    // selector: '.first-component'
    templateUrl: './first.component.html' // relative link to the html file
    // Optional Parameters // styles
    styleUrls: ['./first.component.css', ''] // This is an array of relative paths
})
// Export the class for use
export class FirstComponent {
}
  • Add the following lines to first.component.html
<h3>This is FirstComponent</h3>

Modules

The AppModule can be seen to have a @NgModule declaration which holds 4 key parameters:
1. declarations
2. imports
3. providers
4. bootstrap

The MyOwnComponent that we created in the previous part won’t be recognized by Angular as till now it has no idea that the component exists.
To make sure that Angular knows about the custom component, it is required that it is added to the declarations tag of the AppModule.
Note: Adding the MyOwnComponent name to the declarations tag should throw a compiler error, so make sure to import it first.

The imports parameter makes it easy to import multiple modules to the app, so as to keep the AppModule leaner when the application becomes very large.

Using Custom Components

To know if the MyOwnComponent that we created earlier is working, open the app.component.html file and add the custom selector tag we defined for our component in the file.
Run the application and you should see the “This is MyOwnComponent” on the page

Creating components with the CLI and nexting components

To create components, one can also use the CLI

ng generate component servers // or in short
ng g c servers

This will create a folder named servers and create a few files, namely:
servers.component.ts
servers.component.html
servers.component.css
servers.component.spec.ts – This is the Test Script file and has nothing to do with development and hence can be deleted.

Working with Component Templates

While an external templateUrl can be provided in the Custom Component declaration, one can also use inline templates.
So instead of using templateUrl: ‘/custom.component.html’,
one can also do template: ‘<h1>Custom Tags are allowed</h1>’
also using back-ticks template: ` <h1>Custom Tags are allowed</h1> `

A few things to keep in mind:
1. At least one of them should be present, i.e.- template or templateUrl
2. If defining template, they should not be wrapped to multi-line, as typescript doesn’t support that in a string.
3. If multi-line string is required, then one can use back-ticks ` to wrap code templates.

Working with component styles

Similar to that of the template, the styles can also be defined inline.

styles: [
    h3 {
        color: blue;
    }
]

Fully understanding the Component Selector TODO

While the only selector that has been used till now is:
selector: ‘app-servers’ – This makes for a tag selector, so needs to be used as

<app-servers></app-servers>

This can also be replaced with
selector: ‘[app-servers]’ – This would make it an attribute selector and can be used as

TODO

selector: ‘.app-servers’ – This would make it a class selector and can be used as

<div class="app-servers"></div>

Leave a Reply