[Angular] Getting To Know Angular Components
Автор
Сообщение
news_bot ®
Стаж: 6 лет 9 месяцев
Сообщений: 27286
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:
- In order for a component to be recognized by Angular, it is annotated by a @Component() decorator.
- The logic and behavior of the component are stored in the controller, which is a class decorated by @Component().
- 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.
===========
Источник:
habr.com
===========
Похожие новости:
- [Программирование, Angular] Простая архитектура приложений на фреймворке Angular (перевод)
- [JavaScript, Программирование, Алгоритмы, Функциональное программирование] Решаем вопрос сортировки в JavaScript раз и навсегда
- [Angular] Как быстро и удобно документировать Angular проект с помощью модуля AddOnDoc из TaigaUI
- [Разработка веб-сайтов, JavaScript, Angular, TypeScript] RxJS Challenge: Неделя 1
- [Amazon Web Services, Angular, DevOps] Сам себе DevOps: строим cloud-only CI для веб приложения
- [Программирование, Java] Okta: безопасный доступ к приложениям на Angular + Spring Boot (перевод)
- [JavaScript, Angular, ReactJS] Only 39% of the functions in node_modules are unique in the default Angular project (перевод)
- [JavaScript, Angular, ReactJS] Только 39% функций в node_modules уникальны в дефолтном Angular проекте
- [Angular] Добавляем PWA в Angular приложение
- [Angular, TypeScript] Обмен данными между компонентами Angular
Теги для поиска: #_angular, #_angular, #_component, #_angular
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Текущее время: 22-Ноя 12:44
Часовой пояс: UTC + 5
Автор | Сообщение |
---|---|
news_bot ®
Стаж: 6 лет 9 месяцев |
|
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:
import { Component, OnInit } from '@angular/core';
@Component({ selector: 'example_app', templateUrl: './component.example.html', styleUrls: ['./component.example.css'] }) export class ExampleApp implements OnInit { constructor() { } } <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> 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; } =========== Источник: habr.com =========== Похожие новости:
|
|
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Текущее время: 22-Ноя 12:44
Часовой пояс: UTC + 5