Monday, August 31, 2020

How to Create Components in Angular 9

In this post, you're going to learn about Angular components, how to create and use a component in a project, and what string interpolation is. I will also be covering other important features of Angular in my upcoming articles:

What is a Component?

Components are the most basic building blocks of an Angular application. We can think of components like LEGO pieces. We create a component once but can use them many times as we need in different parts of the project.

An Angular component is made of 3 main parts:

  • HTML Template is View
  • TypeScript File is Model
  • CSS File is Styling

Why do we need Components?

Using components is beneficial in many ways. Components divide the UI into smaller views and render data. A component should not be involved in tasks like making HTTP requests, service operations, routing, and so on. This approach keeps the code clean and separates the view from other parts (see separation of concerns).

How to Create Components in Angular 9


Another important reason is that components divide the code into smaller, reusable pieces. Otherwise, we would have to include endless lines of code in a single HTML file, which makes the code much harder to maintain.

Creating Our First Angular Component

Now let's create our first component. The short way to create a component is by using Angular CLI:

ng g c component-name

g: generate, c: component

This command creates a brand new component with its own files (HTML, CSS, and TypeScript) and registers it to the App Module automatically:



Now let's take a closer look at the component model (TypeScript Component File):

This is actually a TypeScript class but to define it as a component:

First of all, we need to import Component from the @angular/core library, so we can use the component decorator

The @Component decorator marks the class as a component and allows us to add the following metadata

The selector is for calling the component later as an HTML tag: <app-root> </app-root>

TemplateUrl is the path where the HTML View of the component is.

Style URLs (can be more than 1) is where the styling files of the component are.

Finally, we export the class (component) so that we can call it inside the app.module or other places in the project later.

What is String Interpolation?

One of the most common questions people ask about Angular is what that curly braces syntax is. Components render data, but data can change in time, so it needs to be dynamic.

We use curly braces inside other curly braces to render dynamic data: {{ data }} and this representation is called string interpolation. You can see the example in the video version above.

No comments:

Post a Comment