Pull to refresh

Getting To Know Angular Components

Angular

Angular is one of the most popular front-end development frameworks out there. It is a leading choice for personal as well as industry-level development of web applications due to its robust capabilities. While Angular is popular for many different reasons, one of the main ones is its modular nature. Modularity makes it easy for the developer to keep track of all the different elements being used to program functionalities. It also helps in keeping consistency and even reusing a block of code or functionality multiple times.

This modularity lies at the heart of Angular in the form of elements called components. This article will quickly take you through all the important bits to know about Angular components, their usage, how they are useful, and some code examples. Components make Angular easy to learn and applications easy to structure. Through this article, you’ll get to see how Angular components make all of this possible.

What Are Angular Components Exactly?

Components lie at the foundation of Angular applications. They interact similar to how HTML elements do in terms of passing data between elements and emitting events. Each of the components has some behavior attached to it that tells what data to render or load and a template that tells it how to render the data. An Angular application is based on a component tree structure where different components have child components and so on. Data is shared from parent to child components through an ‘input binding.’ Similarly, it can be shared the other way around through outputs.

Components are the first elements to be rendered when bootstrapping and rendering an Angular application. Specifically, the App component is rendered and its child components alongside it. Throughout the user journey of the application, some components are being constantly removed while new ones are loaded and rendered. This continues on until the application is finally closed.

Components are also very helpful in the automated testing of Angular applications. Due to how fundamental they are to the application, testing components is often the most crucial part of testing. The components can be tested using many different frameworks such as Jasmine, Karma, or even Angular’s own testing utilities. More complex components obviously require complex tests for quality assurance, so it is better to create smaller components that can be validated quickly and easily.

What Goes Inside Angular Components?

As mentioned before, a component basically encapsulates instructions on what data is going to be rendered and the visual layout of that rendering. This is achieved by including the following aspects:

  1. In order for a component to be recognized by Angular, it is annotated by a @Component() decorator.

  2. The logic and behavior of the component are stored in the controller, which is a class decorated by @Component().

  3. The visual layout is given in the form of an HTML markup file called a template. The template derives the values of data to bind and render from the controller.

While these are the main pieces that constitute a valid component, many additional attributes can be included as well. Each of these attributes brings in its own functionality and adds a new dimension to the component. Some prominent examples include the data being passed from a parent component in the form of an input or CSS files that define and encapsulate the styling of the visual layout of the component. One can also include code from Angular’s animation library to include transitions and other cool animations into the template. Following is an example of declaring an example component.

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

@Component({
	selector: 'example_app',
	templateUrl: './component.example.html',
	styleUrls: ['./component.example.css']
})

export class ExampleApp implements OnInit { 
  constructor() { }
}

Here, the selector part is telling how the component is to be associated with a certain HTML element in the application's template. The templateUrl basically gives the location for the component’s template HTML file. styleUrls gives the location of a CSS file for additional styling instructions, which works along with the component’s template.

How To Configure An Angular Component?

Once an Angular component has been declared, it is provided with its main logic that defines its functionality. In the example below, you can see how the ExampleApp component is defining data, along with methods, that is further used by the template HTML file that is given below.

<h1>{{ username }}</h1>
<span>Change Name: </span><input [(ngModel)]="username">
<h3>Posts: {{ totalPosts }}</h3>
<ul>
<hr/>
<div *ngFor="let post of posts; let i=index">
	<button (click)="deletePost(i)">DELETE</button>
	<h6>{{ post.title }}</h6>
	<p>{{ post.body }}</p>
	<hr/>
</div>
</ul>

The data defined by the component is used by the HTML file in curly brackets. Alongside that, the deletePost method is bound with the DELETE button and is triggered every time it is pressed. Even the username can be changed through the input box generated by the HTML file.

Including Inputs In Component

Inputs are a necessary part of a component tree structure and the Angular application in general. They can be implemented as shown in the following example.

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

@Component({
	selector: 'example_app',
	templateUrl: './component.example.html',
	styleUrls: ['./component.example.css']
})

export class ExampleApp implements OnInit {
	constructor() { }
}

export class ExampleComponent2 {
	@Input() title: string = '';
	@Input() description: string = '';
	@Input('used') value: number = 0;
	@Input('available') max: number = 100;
}

ExampleComponent2 shows all the different data values that can be received from the parent component. If not passed, they are assigned their default values which are also defined in the component. @Input() helps specify that these variables can receive input and in the last two values, it also provides aliases inside the bracket. These aliases can be used in the HTML file and Angular would still direct them to these variables. @Output() works in a similar way and declares a variable to be a way to pass data to a parent component. The parent’s and child’s template files are then configured to forward and receive data through the specific variables.

Conclusion

It is not possible to use Angular and its powerful abilities without understanding components and how to use them. Learning them and configuring them is the first step towards Angular proficiency. The functionality of components can be further added to through many different ways which help in building complex but innovative web applications. These include functions to observe if an event regarding a component’s lifecycle has occurred (creation, removal, or rendering) called lifecycle hooks. Or pipes that show the transformation of data on the template HTML file, like the TitleCasePipe that takes a string and changes it all to title case.

Tags:angularcomponent
Hubs: Angular
Rating 0
Views247

Popular right now

Angular 9
August 2, 202134,700 ₽Luxoft Training
UI-дизайнер
June 25, 202147,940 ₽Нетология
Python для работы с данными
June 25, 202131,500 ₽Нетология
Веб-дизайнер
June 28, 202183,000 ₽GeekBrains
Основы вёрстки сайтов
June 28, 202120,000 ₽Loftschool

Top of the last 24 hours