ANGULAR

ANGULAR

Angular is a development platform, built onnbsp;TypeScript.As a platform, Angular includes:A component-based framework for building scalable web applicationsA collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and moreA suite of developer tools to help you develop, build, test, and update your codeWith Angular, youre taking advantage of a platform that can scale from single-developer projects to enterprise-level applications. Best of all, the Angular ecosystem consists of a diverse group of over 1.7 million developers, library authors, and content creators.PrerequisitesLike most modern frameworks, Angular expects you to be familiar with HTML, CSS and JavaScript. In addition, it’s recommended to have familiarity with the following concepts and tools:ConceptsJavaScript ClassesTypeScript fundamentalsTypeScript DecoratorsToolsTypeScriptnbsp;- This is shipped by default with every Angular app to provide improved tooling and enhanced maintainability for a better developer experience.Command Line Interface (CLI)nbsp;- Angular uses a compiler in order to abstract tooling complexity and optimize your code so you can focus on building your app.ComponentsComponents are the fundamental building block for creating applications in Angular. By leveraging component architecture, Angular aims to provide structure for organizing your project into manageable, well organized parts with clear responsibilities so that your code is maintainable and scalable.An Angular component can be identified by thenbsp;componentnbsp;suffix (e.g.,nbsp;my-custom-name.component.tsnbsp;and has the following:A decorator to define configuration options for things like:A selector that defines what the tag name is when referring a component in a templateAn HTML template that controls what is rendered to the browserA TypeScript class that defines the behavior of the component. Examples include handling user input, managing state, defining methods, etc.Here is a simplified example of a TodoListItem component.content_copy// 📄 todo-list-item.component.ts @Component({ standalone: true, selector: todo-list-item, template: lt;ligt;(TODO) Read cup of coffee introductionlt;/ligt; , styles: [li { color: papayawhip; }], }) export class TodoListItem { /* Component behavior is defined in here / }BehaviorNow that we have the basic structure for the component, let’s learn more about how you define the component’s behavior.StateWhen defining data that you want the component to manage, this can be accomplished by declaring it by definingnbsp;class fields.In the example of anbsp;todo-list-item.component.ts, there are two properties we want to track:nbsp;taskTitlenbsp;andnbsp;isComplete. Using thenbsp;class field syntax, they can be defined as follows:content_copy// 📄 todo-list-item.component.ts @Component({ ... }) export class TodoList { taskTitle = ; isComplete = false; }MethodsYou can define functions for a component by declaring methods within the component class.content_copy// 📄 todo-list-item.component.ts @Component({ ... }) export class TodoList { taskTitle = ; isComplete = false; updateTitle(newTitle: string) { this.taskTitle = newTitle; } completeTask() { this.isComplete = true; } }TemplatesEvery component has an HTML template that defines what that component renders to the DOM.HTML templates can be defined as an inline template within the TypeScript class, or in separate files with thenbsp;templateUrlnbsp;property. To learn more, check outnbsp;the docs on defining component templates.Within this document, the examples will use inline templates for more concise code snippets.Rendering Dynamic DataWhen you need to display dynamic content in your template, Angular uses the double curly brace syntax in order to distinguish between static and dynamic content.content_copy@Component({ template: lt;pgt;Title: {{ taskTitle }}lt;/pgt; , }) export class TodoListItem { taskTitle = Read cup of coffee; }This is how it renders to the page.content_copylt;pgt;Title: Read cup of coffeelt;/pgt;This syntax declares annbsp;interpolationnbsp;between the dynamic data property inside of the HTML. As a result, whenever the data changes, Angular will automatically update the DOM reflecting the new value of the property.Dynamic Properties and AttributesWhen you need to dynamically set the value of attributes in an HTML element, the target property is wrapped in square brackets. This binds the attribute with the desired dynamic data by informing Angular that the declared value should be interpreted as a JavaScript-like statement (with some Angular enhancements) instead of a plain string.content_copylt;button [disabled]=hasPendingChangesgt;lt;/buttongt;In this example, the disabled property is tied to thenbsp;hasPendingChangesnbsp;variable that Angular would expect to find within the component’s state.Event HandlingYou can bind event listeners by specifying the event name in parenthesis and invoking a method on the right-hand-side of the equals sign:content_copylt;button (click)=saveChanges()gt;Save Changeslt;/buttongt;If you need to pass the event object to your event listener, Angular provides an implicitnbsp;$eventnbsp;variable that can be used inside the function call:content_copylt;button (click)=saveChanges($event)gt;Save Changeslt;/buttongt;StylesWhen you need to style a component, there are two optional properties that you can configure inside of thenbsp;@Componentnbsp;decorator.Similar to component templates, you can manage a components styles in the same file as the TypeScript class, or in separate files with thenbsp;styleUrlsnbsp;properties.Components can optionally include a list of CSS styles that apply to that components DOM:content_copy@Component({ selector: profile-pic, template: lt;img src=profile-photo.jpg alt=Your profile photo /gt;, styles: [ img { border-radius: 50%; } , ], }) export class ProfilePic { / Your code goes here / }By default, a components style will only apply to elements in that components template in order to limit the side effects.To learn more, check outnbsp;the docs on component styling.DirectivesWhen building applications, developers often need to extend on the behavior of an HTML element or Angular directives/components. Examples of this include: displaying content based on a certain condition, rendering a list of items based on application data, changing the styles on an element based on user interaction, etc.To solve this problem, Angular uses the concept of directives, which allow you to add new behaviors to an element in a declarative and reusable way.Conditional renderingOne of the most common scenarios that developers encounter is the desire to show or hide content in templates based on a condition.Similar to JavaScriptsnbsp;ifnbsp;control block, Angular provides a built-innbsp;ngIfnbsp;directive to control whether an element will render if the expression returns a truthy value.content_copylt;section class=admin-controls ngIf=hasAdminPrivilegesgt; The content you are looking for is here. lt;/sectiongt;Ifnbsp;hasAdminPrivilegesnbsp;is true, the application will display the content to the user, otherwise, the element is removed from the DOM entirely.Rendering a listAnother common scenario is to render a list of items based on dynamic data.Similar to JavaScript’snbsp;fornbsp;loop, Angular provides another built-in directive callednbsp;ngFor, The following code will render onenbsp;lt;ligt;nbsp;element for each item innbsp;taskList.content_copylt;ul class=ingredient-listgt; lt;li *ngFor=let task of taskListgt;{{ task }}lt;/ligt; lt;/ulgt;Custom directivesWhile built-in directives help to solve common problems that developers encounter, there are situations where developers require custom behavior that’s specific to their application. In these cases, Angular provides a way for you to create custom directives.Custom Angular directives can be identified by thenbsp;directivenbsp;suffix (e.g.,nbsp;my-custom-name.directive.ts).Similar to defining a component, directives are comprised of the following:A TypeScript decorator to define configuration options for things like:A selector that defines the tag name is when the component is calledA TypeScript class that defines the extended behavior the directive will add to the respective HTML element.For example, here’s a custom directive for highlighting an element:content_copy@Directive({ selector: [appHighlight], }) export class HighlightDirective { private el = inject(ElementRef); constructor() { this.el.nativeElement.style.backgroundColor = yellow; } }To apply this to an element, the directive is called by adding it as an attribute.content_copylt;p appHighlightgt;Look at me!lt;/pgt;Directives can also leverage user events, take input for additional customization, but this goes beyond the scope of this article. To learn more, check outnbsp;the docs on creating custom directives.ServicesWhen you need to share logic between components, Angular allows you to create a “service” which allows you to inject code into components while managing it from a single source of truth.Angular services can be identified by thenbsp;servicenbsp;suffix (e.g.,nbsp;my-custom-name.service.ts).Similar to defining a component, services are comprised of the following:A TypeScript decorator to define configuration options for things like:providedInnbsp;- This allows you to define what parts of the application can access the service. For example, ‘root’ will allow a service to be accessed anywhere within the application.A TypeScript class that defines the desired code that will be accessible when the service is injectedHere is an example of anbsp;Calculatornbsp;service.content_copyimport {Injectable} from @angular/core; @Injectable({ providedIn: root, }) class CalculatorService { add(x: number, y: number) { return x + y; } }If we wanted to call the service in a Receipt component for example, here’s what it might look like:content_copyimport { Component } from @angular/core; import { CalculatorService } from ./calculator.service; @Component({ selector: app-receipt, template: lt;h1gt;The total is {{ totalCost }}lt;/h1gt;, }) export class Receipt { private calculatorService = inject(CalculatorService); totalCost = this.calculatorService.add(50, 25); }In this example, thenbsp;CalculatorServicenbsp;is being used by calling the Angular functionnbsp;injectnbsp;and passing in the service to it.OrganizationStandalone components are a new organizational pattern that were introduced in Angular v15 and is the recommended place to start. In contrast tonbsp;NgModules, it allows developers to organize code and manage dependencies through components rather than feature modules.For example, in the traditional NgModule pattern, you would need to create a TodoModule and manage all of its dependencies through this module.content_copyimport {NgModule} from @angular/core; import {FormsModule} from @angular/forms; import {TodoList} from ../todo/todo-list.component; @NgModule({ declarations: [TodoList], imports: [FormsModule], exports: [TodoList, FormsModule], }) export class TodoModule {}However, you can now achieve something similar with a standalone component without the need for a module file:content_copyimport {FormsModule} from @angular/forms; import {TodoList} from ../todo/todo-list.component; @Component({ standalone: true, selector: todo-app, imports: [FormsModule, TodoList], template: ... lt;todo-list [tasks]=taskListgt;lt;/todo-listgt; , }) export class PhotoGalleryComponent { // component logic }While most of this should be familiar (from the Components section), two things that are unique to this new pattern are thenbsp;standalonenbsp;flag and thenbsp;importsnbsp;key.standalonenbsp;- When provided the valuenbsp;true, this tells Angular that the component does not need to be declared in an NgModuleimportsnbsp;- Allows developers to declare what dependencies will be used in the componentIn other words, rather than having to define a specific context in which code should be organized, developers are able to specify the dependencies directly within the component context itself.Command Line Interface (CLI)The Angular CLI is the recommended way to develop Angular applications and can make some tasks trouble-free.Some examples of common Angular CLI commands include:CommandDetailsng buildCompiles an Angular application into an output directory.ng serveBuilds and serves your application, rebuilding on file changes.ng generateGenerates or modifies files based on a schematic.ng testRuns unit tests on a given project.ng e2eBuilds and serves an Angular application, then runs end-to-end tests.For more information about the Angular CLI, see thenbsp;Angular CLI Referencenbsp;section.First-party librariesAngular provides many first-party libraries to support common functionality that developers often encounter when building their apps.Some of the popular libraries available in the ecosystem include:LibraryDetailsAngular RouterAdvanced client-side navigation and routing based on Angular components. Supports lazy-loading, nested routes, custom path matching, and more.Angular FormsUniform system for form participation and validation.Angular HttpClientRobust HTTP client that can power more advanced client-server communication.Angular AnimationsRich system for driving animations based on application state.Angular PWATools for building Progressive Web Applications (PWA) including a service worker and Web application manifest.Angular SchematicsAutomated scaffolding, refactoring, and update tools that simplify development at large scale.

To view or add a comment, sign in

More articles by Muskan Singh

  • TABLEAU

    Tableau is a leading Business Intelligence (BI) and data visualization tool designed to make data analysis accessible…

  • PRODUCT MANAGEMENT

    What is product management? Product management involves coordinating and overseeing each stage of the product life…

  • TEST AUTOMATION

    Test automation is the process of using software tools and scripts to execute and validate tests automatically. It…

  • ETL Testing

    ETL Testing refers to the process of validating, verifying, and ensuring the accuracy, integrity, and performance of…

  • DATABASE DEVELOPER

    A database developer is a specialized software developer who designs, implements, and maintains databases. They play a…

  • DATA ANALYST

    A data analyst is a professional who collects, cleans, and interprets data sets to help solve problems and make…

  • DATA ENTRY

    Data entry can refer to any of the following: 1. Data entry is the inputting of data or information into a computer…

  • JAVA DEVELOPER

    Java is one of the most widely used programming languages in the world. Talking about its popularity, more than nine…

  • ML ENGINEER

    Machine learning engineers are responsible for building artificial intelligence systems. This fascinating branch of…

  • ANGULAR

    Angular is a powerful and versatile web application framework maintained by Google and a community of developers. It is…

Insights from the community

Others also viewed

Explore topics