Learnitweb

Component in Angular

In this article, we’ll learn what a component is, in Angular. We’ll create our own component and see how to use it.

What is a component?

Components are the main building block of Angular applications. It is the component where the logic of the application is written. An Angular application is usually made up of multiple components. For example, suppose there is a page with a header, footer and the main content of the page. We can break it down to three components, header component, footer component and body component. We can further break down the body component in several other components, if required.

Angular components are a subset of directives. A component is always associated with a template. Only one component can be instantiated for a given element in a template. Only one component can be instantiated for a given element in a template. If the component is required and made available to another component or application, the component must belong to an NgModule. To make a component, a member of an NgModule, we add the component in the declarations field of the NgModule metadata.

Each component consists of the following:

  • An HTML template that declares what is rendered on the page for the component.
  • A Typescript class which contains the application logic that this component is supposed to execute.
  • A CSS selector that defines how the component is identified and used in a template.
  • A file containing styles to be applied to the component. It is optional to have such file.

Creating a component

The easiest way to create a component is with the Angular CLI. We can also create a component manually but in that case we have to write a bit of boilerplate code. We’ll use the Angular CLI to create our component.

Create a component with Angular CLI

  • Step 1: Navigate to the root directory of your application.
  • Step 2: Run the ng generate <component-name> command. The short form of this command is:
    ng g c <component-name>
    Here, <component-name> is the name of the component.

This will create our component with name <component-name>. Following will be created in the system:

  • A directory having name as <component-name>.
  • An HTML template having name as <component-name>.component.html.
  • A Typescript file having name as <component-name>.component.ts.
  • A CSS file having name as <component-name>.component.css.
  • A testing specification file having name as <component-name>.component.spec.ts.

Let us now create our own component using Angular CLI. We’ll name it as my-component.

ng generate component <my-component>

This will generate my-component directory having following files:

  • A component file, <my-component>.component.ts.
  • A template file, <my-component>.component.html.
  • A CSS file, <my-component>.component.css.
  • A testing specification file, <my-component>.component.spec.ts.

Note: ng generate will also add this component in the declarations list of app.module.ts file.

Let us now look each file and it’s content.

Component file – <component-name>.component.ts

This is the file which contains the logic of our application. In our case the file is my-component.component.ts. The content of this auto-generated file is:

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

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

  constructor() { }

  ngOnInit(): void {
  }

}
  • At the top of the file, there is an import statement.
import { Component, OnInit } from '@angular/core';

In auto-generated file OnInit is imported and used, but it is not mandatory when we create component manually.

  • After the import statement, there is a @Component decorator.
@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})

@Component decorator marks a class as an Angular component. It is mandatory to make a class as a component.

There are three options which can be configured for @Component decorator.

  1. selector: This is a CSS selector that identifies this directive in a template. In easy way to understand, we can say that a component is identified by it’s selector. Wherever the selector is found in code, the component is initialized at it’s place.
  2. templateUrl: A component is always associated with a template. templateUrl specifies the relative path or absolute URL of a template file. We can also provide an inline template as well with template option.
  3. styleUrls: This specifies the one or more relative paths or absolute URLs for CSS files used in this component. We can also provide inline style by using styles option instead of styleUrls.
  • Next is the code of the component. OnInit is the interface, ngOnInit is the method of OnInit. There is one default constructor also auto-generated for us.
export class MyComponentComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

Template file – <component-name>.component.html

This is the template file associated with the component. In simple term, this is how a component looks like when used. The file generated for us is:

<p>my-component works!</p>

CSS file – <component-name>.component.css

This file is empty by default. All the styles to be used by the component are added in this file.

Testing specification file – <component-name>.component.spec.ts

This is a testing specification file. We’ll discuss about it later in the testing section. The content of this file is:

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { MyComponentComponent } from './my-component.component';

describe('MyComponentComponent', () => {
  let component: MyComponentComponent;
  let fixture: ComponentFixture<MyComponentComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ MyComponentComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

How to use a component we created?

It is very simple to use the component we created. Suppose we want to use the component in another component. What we have to do is just use the selector of the component in the template of another component. For example, if we want to use my-component in app-component, we can write :

<h1>App Component</h1>
<app-my-component></app-my-component>

Conclusion

In this article, we learned what a component is and created our first component. In next article, we’ll see how to define inline template and styles in a component.