Angular 2 Component


Angular 2 Component

An Angular 2 component is combination of an HTML template, Class and metadata that controls a portion of the screen.

Angular 2 Component
Angular 2 Component
  1. Template – Here template is nothing but a HTML page which used to layout the view.
  2. Class –  Inside class we can write our methods and properties variables.
  3. Metadata –  Metadata used to provide extra meta data for Angular and it’s defined with decorator.

Our Angular Component will look like below.

import { Component } from '@angular/core';
 @Component({
    selector:'root',
    template:'<h1>Root</h1>'
 })
 export class AppComponent{
    //properties
 }

Here @Component is decorator which provides metadata.

Creating the Component class

We have to follow some steps to create Angular 2 component.

  1. Create a class with export and class keyword.
  2. Provide metadata on above created class with @Componentdirective.

Here @Component adds metadata to class, its member or its method arguments.

import { Component } from '@angular/core';
 
@Component({
   selector:'app-root',
   template:'<h1>{{pageTitle}}',
})
 
export class AppComponent{
    pageTitle: string = "Angular 2 Component";
}

Here let’s understand what is selector and template

  1. selector –      To reference this component in any HTML page this selector will be used. It represent the custom HTML page.
  2. template-    A Component should always have a template here we will define the layout.

Example

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

@Component({
  selector:'name',
  template:'<h1>{{name}}</h1>'
})

export class NameComponent {
    name: string = "Vikas Kumar";
    constructor() { }
}

Note – To be able to use this new component we need to update our module, otherwise Angular is not going to be able to compile our application.






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229