Angular Component

 

Components are the main building block for Angular applications. 

Each component consists of:

  • An HTML template that declares what renders on the page
  • A TypeScript class that defines behavior
  • A CSS selector that defines how the component is used in a template
  • Optionally, CSS styles applied to the template

Lets start with creating a new component with name demo

ng generate component demo

By default, this command creates the following:

  • A folder named after the component
  • A component file, <component-name>.component.ts
  • A template file, <component-name>.component.html
  • A CSS file, <component-name>.component.css
  • A testing specification file, <component-name>.component.spec.ts

After invoking above command following files will be created in src/app/demo folder

 

 

demo.component.ts

As mentioned earlier, the @Component decorator accepts a metadata object that provides information about the component. Here’s a list of properties of the metadata object: 

selectorA CSS selector that tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML. For example, if an application's HTML contains <app-demo></app-demo>, then Angular inserts an instance of the DemoComponent view between those tags.
templateUrlThe module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the template property. This template defines the component's host view.
providersAn array of providers for services that the component requires. In the example, this tells Angular how to provide the DemoService instance that the component's constructor uses to get the list of heroes to display.

 

demo.component.html

  • This file contains html code for component

 

demo.component.css

  • This file contains style required for component

 

Variables in component

We can declare variables as below

name: string;
age:number;
users:Array<User>;
currentCustomer: string = “demo”;

Functions/Methods in component

Submit(name:string){
 this.name= name;
}

 

Variables and Functions

 

Data binding

 

Interpolation Binding 

Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly brace ({{ and }}) characters as delimiters.

<h3>Current customer: {{ currentCustomer }}</h3>
<div><img alt="item" src="{{itemImageUrl}}"></div>