Ad

Angular the series Part 4: Component and Module



    Component is a key feature in Angular. You build your application by composing it from a couple of components.

    Each component encapsulates the data, the HML template, and the logic. That leads to a great benefit: you can split your complex application into small reusable and maintainable parts.

    Let's imagine we have an online shopping web application. Instead of implementing the whole logic in one single file, we can split it in smaller parts, like ProductsComponent will contain the logic to show all products, which can be a ProductDetailComponent, inside a grid, ShoppingCartComponent will take responsible for showing the items that user has chosen and payment, and so on. That makes the source code more readable, easy to maintain and reuse.
    Every Angular application has at least one component we called AppComponent or root component. A real world app is essentially a tree of Components, starting from that root component.

    In Angular, we also have another concept called Module. A module contains a group of related components, and each component can only be added of exactly one module. Every Angular application has at least one module called AppModule. So, if you're building a single application, we have only one module, which is AppModule. But as our application grows in functionality, we need to break that module into some smaller ones, with each of them takes responsible for specific area of our application.

    Back to the example in the beginning of this section, for our online shopping web application, we can have ProductModule which includes all the components for displaying products, ProfileModule which includes all the components for displaying the user account information, the AdminModule for administrator to manage to website, and so on.

    Now, let's see these components in action. First of all, you must know how to create a component.

    One of the easiest way to create component is with Angular CLI. Just run the command and Angular CLI will take care all of that, from creating all the files you need to registering that new component to the AppModule. Of course, you can do it manually if you want.

    So, if you want to work with Angular CLI, from the terminal window, navigate to the folder you want to create your component and run the command:
ng generate component <component-name>
CREATE src/app/my-new-component/my-new-component.component.html (31 bytes) 
CREATE src/app/my-new-component/my-new-component.component.spec.ts (686 bytes) 
CREATE src/app/my-new-component/my-new-component.component.ts (314 bytes) 
CREATE src/app/my-new-component/my-new-component.component.scss (0 bytes) 
UPDATE src/app/app.module.ts (601 bytes)
    By default, this command creates a new folder named after the <component-name>, for example:
  • <component-name>.component.ts: component file, contains all the business logic
  • <component-name>.component.spec.ts: testing specification file.
  • <component-name>.html: template file
  • <component-name>.scss: stylesheet file
It also registers the new component to our AppModule.
app.module.tsimport { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';       
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MyNewComponentComponent } from './my-new-component/my-new-component.component';
        
@NgModule({
  declarations: [
    AppComponent,
    MyNewComponentComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
    Now, take a look at our component file. We can see something like @Component. It is a Decorator, and we can attach it to a class to make it a component. Basically it is like a function, and it takes an argument. So, we will pass an object and in this object, we add one or more properties to tell Angular how this component works.
my-new-component.component.tsimport { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-new-component',
  templateUrl: './my-new-component.component.html',
  styleUrls: ['./my-new-component.component.scss']
})
export class MyNewComponentComponent implements OnInit {
  constructor() { }

  ngOnInit(): void {
  }
}

  One properties that we use quite often is selector. It should be a string and you can set up any name you want, but make sure it is unique. And this is something that you can use in your other component HTML files.

  The second property is templateUrl, and that contains a relative path to the HTML markup we want to be rendered for this component.

  Another property is styleUrls. You can pass a list of relative paths to CSS files that you want to apply the style to the component template.

  When creating a new component with Angular CLI, it will take care all of that and saves us a lot of time. So now, when we've already had our own component, how can we use it? Back to the app folder, we have the app.component.html. Just clear everything in this file and place something like this:
app.component.html<h1>Angular</h1>
<app-my-new-component></app-my-new-component>  
<app-my-new-component> is the selector of my new component just like above. You can place your own element. So when Angular sees this element, it will render the template of our custom component, in this example is MyNewComponentComponent.

Just save the work and serve the application, then open the browser and you can see something like this:

As you see, in the elements window on the right side, you can see the <app-root>. Back in the src/ folder, look at the index.html, it's the basic template for our application, and you can see inside the body element is the <app-root>.
index.html<html lang="en">
    
<head>
  <meta charset="utf-8"></meta>
  <title>My First Angular Project</title>
  <base href="/"></base>
  <meta content="width=device-width, initial-scale=1" name="viewport"></meta>
  <link href="favicon.ico" rel="icon" type="image/x-icon"></link>
</head>
    
<body>
  <app-root></app-root>
</body>
    
</html>
    
This is the custom element, because you don't have any HTML tag called <app-root>. So whenever Angular see this kind of element, it will find and render the template for this component inside that element. In this case, it is our AppComponent. And also inside the AppComponent, we use another component which we just created, that's why we have the template for our own component inside the <app-root>.

And that's how you can create and use a component in Angular. I'll see you in the next section.