Saturday, April 22, 2023

Angular- Component

angular component

Angular is a framework for developing SPA applications. A SPA application view is made of one or more components. A component represents the view in the Angular application.

Components are the main building block for any Angular application. Each component consists of the following: 

  1. HTML template that declares what renders on the page 
  2. A TypeScript class that defines the behavior
  3. Component Metadata
Angular Component

HTML Template

HTML template is nothing a regular HTML code with angular-specific syntax to communicate with the component class.

Component Class

A component class is a TypeScript class that includes properties and methods. Properties store data and methods include the logic for the component.

Component Metadata

Metadata is some extra data for a component used by Angular API to execute the component, such as the location of HTML and CSS files of the component, selector, providers, etc.

Generate Angular Component using Angular CLI

We can create an angular component manually or using Angular CLI. Here we will see how to create component using CLI.
 
Use the following CLI command to generate a component.
ng generate component <component name>
The following executes the ng g command to generate the example component-
create angular component
In above, example.component.css is a CSS file for the component, example.component.html is an HTML file for the component where we will write HTML for a component, example.component.spec.ts is a test file where we can write unit tests for a component, and example.component.ts is the class file for a component.
When you will open the example.component.ts file in your editor, you we see below code in the file.
import { Component } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {

}
Following figure will explain different part of component class file-
component class

The example.component.ts includes the following parts:

Component Class

ExampleComponent is the component class. It contains properties and methods to interact with the view through an Angular API.

Metadata

The @Component is a decorator used to specify the metadata for the component class defined immediately below it. It is a function and can include different configs for the component. All Angular components must have @Component decorator above the component class.

The import statement gets the required feature from the Angular or other libraries. Import allows us to use exported members from external modules.

No comments:

Post a Comment

^ Scroll to Top