Angular Components
In this article, We will learn about the Angular Components. It is subset of directives, Angular components are always coupled with a template. Only one component can be instantiated for each element in a template, unlike other directives. To be available to another component or application, a component must be part of a NgModule.
A component is an HTML template combined with a component class that controls a piece of the screen. Every component starts with a metadata object and a @Component decorator method. The metadata object details the interaction between the HTML template and component class. A component is basically anything that is visible to the user and may be reused multiple times within an application.
Angular Component = HTML Template + Component Class + Component Metadata
We use the TypeScript decorator @Component to change the definition of a class or function and add metadata to properties and function arguments.
- Selector: It is the element attribute that instructs Angular to construct and insert a component instance.
- Template: It's a type of HTML that informs Angular how to render content in the DOM.
- MetaData: This is more information for the Angular class. A decorator is used to define it.
HTML Template:
HTML template is just plain HTML with some Angular-specific syntax for communicating with the component class.
Class:
A component class is essentially a TypeScript class with properties and functions. Data is stored in properties, while the component's logic is contained in methods. This class will eventually be compiled into JavaScript.
Metadata:
Metadata is additional information about a component that is utilized by the Angular API to execute it, such as the location of the component's HTML and CSS files, selectors, providers, and so on.
Create New Angular Component using Angular CLI
You can manually create component files or use the Angular CLI tool. The Angular CLI reduces the development time. So, let's we create a new component with Angular CLI.
To create a component, use the CLI command below.
ng generate component <component name>
ORng g c <component name>
g stands for generate
Component Naming Convention
<component-name>.component.<file-type>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
export class TodoComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
name: string = "Steve";
todo(): void {
alert("Hello " + this.name);
};
}
<div>
Enter Your Name: <input type="text" value={{name}} /> <br />
<button (click)="todo()">Todo!</button>
</div>
We used the name attribute in the {{}} interpolation to display its value in the above HTML template, and the todo() method as a click event. Learn more about it in the section on event binding.