Angular Components

In this angular 2 component tutorial, learn what is a component in angular, how to create angular components, angular component metadata with example.

1. What is an angular component

A angular component controls a part of the screen called view. The application logic to support various functions like data binding, event binding, etc. in the view is written inside a class file most commonly named as ‘app.component.ts‘.

2. When to use angular component

Angular component should be used when an application is based on component based architecture and the user interface is divided into smaller web components where each component serves different functionality.

For example, a website might have one component for capturing feedback and another for social media tracking.

3. How to create angular components

We can create angular component either using angular CLI (command line interface) or manually.

3.1. Create component with @angular/cli

A new angular component (e.g. ‘Zipcode’) component can be created using @angular/cli using the command below:

// command: ng generate component [name]

$ ng generate component zipcode

The above command will create the following files inside a new folder named zipcode under src:

  • zipcode.component.html: This html file contains the code/template associated with component e.g.
    <div><strong>zipcode works!</strong></div>
    
  • zipcode.component.spec.ts: This file contains the unit testing related code e.g.
            import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    
            import { ZipcodeComponent } from './zipcode.component';
    
            describe('ZipcodeComponent', () => {
            let component: ZipcodeComponent;
            let fixture: ComponentFixture<ZipcodeComponent>;
    
            beforeEach(async(() => {
                TestBed.configureTestingModule({
                declarations: [ ZipcodeComponent ]
                })
                .compileComponents();
            }));
    
            beforeEach(() => {
                fixture = TestBed.createComponent(ZipcodeComponent);
                component = fixture.componentInstance;
                fixture.detectChanges();
            });
    
            it('should create', () => {
                expect(component).toBeTruthy();
            });
            });
    
         
  • zipcode.component.ts: The component class containing the logic to support the funtionality on view e.g.
            import { Component, OnInit } from '@angular/core';
    
            @Component({
            selector: 'app-zipcode',
            templateUrl: './zipcode.component.html',
            styleUrls: ['./zipcode.component.css']
            })
            export class ZipcodeComponent implements OnInit {
    
            constructor() { }
    
            ngOnInit() {
            }
    
            }
         
  • zipcode.component.css: The CSS file containing stylesheets associated to the component e.g.
         /* ZipcodeComponent's private CSS styles */
            h1 {
            font-size: 1.2em;
            color: #999;
            margin-bottom: 0;
            }
            h2 {
            font-size: 2em;
            margin-top: 0;
            padding-top: 0;
            }
         

3.2. Create component manually

We can manually create the above mentioned files as per our requirement but to create a component we only need to define the mandatory file ‘zipcode.component.ts‘ inside folder zipcode.

4. How to import angular component

After the creation of component, we need to tell angular to load the component by importing it in file ‘app.module.ts‘ as shown below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroSearchComponent } from './hero-search/hero-search.component';
import { MessagesComponent } from './messages/messages.component';
import { ZipcodeComponent } from './zipcode/zipcode.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    HttpClientModule,

    // The HttpClientInMemoryWebApiModule module intercepts HTTP requests
    // and returns simulated server responses.
    // Remove it when a real server is ready to receive requests.
    HttpClientInMemoryWebApiModule.forRoot(
      InMemoryDataService, { dataEncapsulation: false }
    )
  ],
  declarations: [
    AppComponent,
    DashboardComponent,
    HeroesComponent,
    HeroDetailComponent,
    MessagesComponent,
    HeroSearchComponent,
    ZipcodeComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

If the component is generated using @angular/cli command ng generate component zipcode then it will make the above highlighted changes automatically else we have to do it manually.

5. Angular component metadata

The component metadata refers to the properties defined in the @Component decorator. The @Component decorator identifies the class immediately below as the component class.

Metadata associates a template with the component, either directly with inline code, or by reference. Together, the component and its template describe a view.

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

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

  ngOnInit() {
  }
}

Following are the most used properties defined in metadata:

  • selector: A CSS selector helps Angular to create and insert an instance of the component wherever it finds the corresponding tag in template HTML.
  • templateUrl: The module-relative address of the component’s HTML template.
  • template: The inline HTML template defined in `//html stuff goes here`.
  • styleUrls: One or more URLs for files containing CSS style-sheets specific only to this component.
  • styles: One or more inline CSS style-sheets specific only to this component.

Happy Learning!!

Read More : Angular Docs

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.