Angular Training Tutorial https://edupoly.in Indepth Training on ReactJS, Angular, Javascript, MERN,MEAN,Python,Java,Devops,AWS Mon, 13 May 2024 14:10:28 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://edupoly.in/wp-content/uploads/2024/03/edupoly-logo-light-150x150.png Angular Training Tutorial https://edupoly.in 32 32 1. What is Angular https://edupoly.in/angular-training-tutorial/angular-basics-level1/1-what-is-angular/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/1-what-is-angular/#respond Mon, 13 May 2024 12:44:43 +0000 https://edupoly.in/?p=252

Angular is an open-source web application framework developed by Google. It is widely used for building dynamic and interactive single-page applications (SPAs). Angular follows the Model-View-Controller (MVC) architectural pattern and offers a comprehensive set of tools and features for developing complex web applications.

Here are some key aspects of the Angular framework:

TypeScript: Angular is built using TypeScript, a statically typed superset of JavaScript. TypeScript adds features like static typing, classes, interfaces, and modules, which enhance the development experience and help catch errors early.

Components: Angular applications are composed of reusable building blocks called components. A component represents a part of the user interface and encapsulates its own logic, data, and templates. Components can be nested within each other to create complex UI structures.

Templates and Data Binding: Angular’s templates are written in HTML and contain the markup and bindings that define how the application should be rendered. Templates can include dynamic data using Angular’s data binding syntax, allowing developers to create responsive and interactive user interfaces. Data binding enables automatic synchronization of data between the component and the template, allowing for a dynamic and interactive UI.

Directives: Angular provides a variety of directives that extend HTML with additional functionality. Directives allow you to manipulate the DOM, add or remove elements, apply styles dynamically, and more. Angular has built-in directives like *ngIf, *ngFor, and *ngSwitch that are commonly used for conditional rendering and iteration.

Services: Services in Angular are used to encapsulate reusable business logic and data operations. They are typically used for tasks like fetching data from APIs, handling data transformations, or sharing data between components. Services are injected into components using Angular’s dependency injection mechanism.

Routing: Angular offers a powerful routing module that enables navigation between different views within an application. Developers can define routes and associate them with specific components, allowing users to navigate through the application by changing the URL.

Forms: Angular offers powerful form handling capabilities, including two-way data binding, form validation, and form submission. It supports both template-driven forms and reactive forms, providing flexibility based on the requirements.

Testing: Angular provides a robust testing framework with tools like Karma and Jasmine. These tools allow you to write unit tests, integration tests, and end-to-end tests to ensure the quality and stability of your application.

Reactive Programming: Angular embraces reactive programming principles using the RxJS library. Reactive programming allows developers to handle asynchronous operations, event streams, and data manipulation in a declarative and composable manner.

Cross-platform development: With Angular, you can build not only web applications but also cross-platform mobile applications using frameworks like Ionic or NativeScript. Angular’s component-based architecture and code reusability make it easier to develop applications for multiple platforms.

CLI Tool: Angular CLI (Command Line Interface) is a powerful tool that helps streamline the development process. It provides generators for creating components, services, modules, and other artifacts, as well as commands for building, testing, and deploying Angular applications.

These are just some of the features that Angular offers. With its comprehensive toolkit, Angular is well-suited for building large-scale, enterprise-grade web applications with rich user interfaces and complex data handling requirements.

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/1-what-is-angular/feed/ 0 252
2. Angular setup with Angular CLI https://edupoly.in/angular-training-tutorial/angular-basics-level1/2-angular-setup-with-angular-cli-2/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/2-angular-setup-with-angular-cli-2/#respond Mon, 13 May 2024 12:46:46 +0000 https://edupoly.in/?p=254

Angular CLI (Command Line Interface) is a powerful development tool that simplifies the process of creating, managing, and deploying Angular applications. It provides a set of commands and utilities to scaffold, build, test, and serve Angular projects, making the development workflow more efficient. Here’s a detailed explanation of Angular CLI and its key features:

Installation:

To install Angular CLI, you need to have Node.js and npm (Node Package Manager) installed on your machine. Angular CLI is installed globally using npm (Node Package Manager). You can install it by running the following command:

npm install -g @angular/cli

Creating a new project:

Once Angular CLI is installed, you can create a new Angular project using the ng new command. For example:

ng new my-app

This command generates a new Angular project in a folder named “my-app” with the necessary file structure and configuration as shown below. It also installs all the necessary dependencies defined in the package.json file.

Project structure:

Angular CLI sets up a predefined project structure that follows Angular’s best practices. It includes folders for components, modules, services, assets, and more.

The main files are:

  • src/app: Contains the application’s components, services, and other Angular-related files.
  • src/assets: Stores static files like images, fonts, etc.
  • angular.json: The configuration file that defines build and project settings.
  • package.json: Lists project dependencies and scripts.

Development server:

Angular CLI provides a built-in development server that allows you to run your application locally during development.

Use the ng serve command to start the development server:

  1. Navigate to the workspace folder, such as my-project.
  2. Run the following command in a terminal:

ng serve –open

The ng serve command launches the server, watches your files, and rebuilds the app as you make changes to those files.

The –open (or just -o) option automatically opens your browser to http://localhost:4200/.

It also enables hot module replacement, which means any changes you make to your code will automatically trigger a rebuild and update the browser without a full page reload.

Generating components, services, and more:

Angular CLI offers generators to quickly create components, services, modules, and other Angular artifacts.

For example, you can create a new component using the ng generate component command:

ng generate component my-component

This command creates the necessary files for a new component, including the TypeScript code, HTML template, and CSS styles.

Building the application:

Angular CLI provides a command to build your application for production deployment. The build process optimizes your code and generates static files that can be deployed to a web server. You can run the following command:

ng build

Running ng build generates a production-ready build of your application in the dist/ directory.

The build process includes transpiling TypeScript to JavaScript, bundling and minifying files, and optimizing the application for better performance.

Testing the application:

Angular CLI supports unit testing out of the box.

For unit tests, you can use the ng test command to run your test suites using Karma, a popular test runner.

Quiz:

Which command is used to install Angular globally?

a) ng install angular

b) npm install -g @angular/cli

c) ng global add angular

d) npm add -g angular

What is the command to create a new Angular project?

a) ng create my-project

b) ng new my-project

c) ng generate my-project

d) ng init my-project

Which file contains the configuration settings for an Angular project created with Angular CLI?

a) package.json

b) angular.json

c) tsconfig.json

d) index.html

Correct answer: b) angular.json

Which command is used to start the Angular development server?

a) ng serve

b) npm start

c) ng start

d) npm serve

Which command is used to build a production-ready Angular application?

a) ng build

b) npm run build

c) ng compile

d) npm build

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/2-angular-setup-with-angular-cli-2/feed/ 0 254
3. Angular module structure https://edupoly.in/angular-training-tutorial/angular-basics-level1/3-angular-module-structure/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/3-angular-module-structure/#respond Mon, 13 May 2024 12:50:21 +0000 https://edupoly.in/?p=256

Angular is a popular framework for building web applications. It follows a modular architecture that helps in organizing and managing the codebase effectively. Angular has its own modularity system called NgModules. NgModules in Angular are containers that group related components, directives, services, and other features into cohesive units. They provide a way to organize and separate concerns within an application. They can import functionality that is exported from other NgModules, and export selected functionality for use by other NgModules.

Every Angular application has at least one NgModule class, the root module, which is conventionally named AppModule and resides in a file named app.module.ts. This must be present for bootstrapping the application on launch.

  1. A brief look at the App Module

When you use the Angular CLI command ng new to generate an app, the default AppModule looks like the following:

/* JavaScript imports */

import { BrowserModule } from ‘@angular/platform-browser’;

import { NgModule } from ‘@angular/core’;

import { AppComponent } from ‘./app.component’;

/* the AppModule class with the @NgModule decorator */

@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

After the import statements, is a class with the @NgModule decorator.

      The @NgModule decorator identifies AppModule as an NgModule class. @NgModule takes a metadata object that tells Angular how to compile and launch the application. The metadata object identifies the module’s own components, directives, and pipes, making some of them public, through the exports property, so that external components can use them. @NgModule can also add service providers to the application dependency injectors.

NgModule metadata does the following:

  • Declares which components, directives, and pipes belong to the module.
  • Makes some of those components, directives, and pipes public so that other module’s component templates can use them.
  • Imports other modules with the components, directives, and pipes that components in the current module need.
  • Provides services that other application components can use.
  1. The declarations array

The module’s declarations array tells Angular which components belong to that module. As you create more components, add them to declarations.

The declarations array only takes declarables. Declarables are components, directives and pipes. All of a module’s declarables must be in the declarations array. Declarables must belong to exactly one module. The compiler emits an error if you try to declare the same class in more than one module. 

An example of what goes into a declarations array follows:

declarations: [

  YourComponent,

  YourPipe,

  YourDirective

],

  1. The imports array

The module’s imports array appears exclusively in the @NgModule metadata object. It tells Angular about other NgModules that this particular module needs to function properly.

imports: [

  BrowserModule,

  FormsModule,

  HttpClientModule

],

This list of modules are those that export components, directives, or pipes that component templates in this module reference.

  1. The providers array

The providers array is where you list the services the application needs. It is the set of injectable objects that are available in the injector of this module. Dependencies whose providers are listed here become available for injection into any component, directive, pipe or service that is a child of this injector.

providers: [UserService]

Quiz:

What is the purpose of the AppModule in an Angular application?

a) It defines the main component of the application.

b) It handles HTTP requests and responses.

c) It imports and configures other modules.

d) It provides routing for the application.

Which decorator is used to denote an Angular module?

a) @Module

b) @module

c) @ngModule

d) @NgModule

What is the purpose of the declarations array?

a) It helps in importing other modules that this particular module needs to function properly.

b) It tells Angular which components belong to that module.

c) It tells Angular which services the application needs.

d) It provides routing for the application.

What is the purpose of the imports array?

a) It helps in importing other modules that this particular module needs to function properly.

b) It tells Angular which components belong to that module.

c) It tells Angular which services the application needs.

d) It provides routing for the application.

What is the purpose of the providers array?

a) It helps in importing other modules that this particular module needs to function properly.

b) It tells Angular which components belong to that module.

c) It tells Angular which services the application needs.

d) It provides routing for the application.

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/3-angular-module-structure/feed/ 0 256
4. Component creation and nesting https://edupoly.in/angular-training-tutorial/angular-basics-level1/4-component-creation-and-nesting/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/4-component-creation-and-nesting/#respond Mon, 13 May 2024 12:00:01 +0000 https://edupoly.in/?p=198

Components are the main building block for Angular applications. They control patches of screen called views, which are sets of screen elements that Angular can choose among and modify according to your program logic and data. 

Each component consists of:

  • An HTML template that declares what renders on the page
  • A Typescript class that defines behavior
  • A CSS selector that defines how the component is used in a template
  • Optionally, CSS styles applied to the template

a. Creating components using the CLI

To create a component using the Angular CLI:

  1. From a terminal window, navigate to the directory containing your application.
  2. Run the ng generate component <component-name> command, where <component-name> is the name of your new component.

ng generate component example

By default, this command creates the following:

  • A folder named after the component.
  • A component file, example.component.ts
  • A template file, example.component.html
  • A CSS file, example.component.css
  • A testing specification file, example.component.spec.ts

b. Understanding the component file

We define a component’s application logic—what it does to support the view—inside a class. The class interacts with the view through an API of properties and methods. This class is just a normal class unless and until we mark it as a component with the @Component decorator.

i. The @Component decorator

   The @Component decorator identifies the class immediately below it as a  component class, and specifies its metadata. The metadata for a component tells Angular where to get the major building blocks that it needs to create and present the component and its view. In particular, it associates a template with the component, either directly with inline code, or by reference. Together, the component and its template describe a view. In addition to containing or pointing to the template, the @Component metadata configures, for example, how the component can be referenced in HTML and what services it requires.

Here’s an example of basic metadata for ExampleComponent:

@Component({

 selector:    ‘app-example’,

 templateUrl: ‘./example.component.html’,

 styleUrls:  [ ‘./example.component.css’]

})

export class ExampleComponent {

/* . . . */

}

ii. The selector

A CSS selector tells Angular to create and insert an instance of this             component wherever it finds the corresponding tag in template HTML. For example, if an application’s HTML contains <app-example></app-example>, then Angular inserts an instance of the ExampleComponent view between those tags.

iii. The templateUrl

The templateUrl is the relative path or absolute URL of a template file for an Angular component. It defines the HTML template that the component uses to display information. In most cases, this template is a separate HTML file. A template is a block of HTML that tells Angular how to render the component in your application. You can define a template for your component in one of two ways: by referencing an external file, or directly within the component.

To define a template as an external file, add a templateUrl property to the @Component decorator:

@Component({

  selector: ‘app-example’,

  templateUrl: ‘./example.component.html’,

})

To define a template within the component, add a template property to the @Component decorator that contains the HTML you want to use:

@Component({

  selector: ‘app-example’,

  template: ‘<h1>My Example</h1>’,

})

If you want your template to span multiple lines, you can use backticks ( ` ). For example:

@Component({

  selector: ‘app-example’,

  template: `<h1>My Example</h1>

             <p>This template definition spans

              multiple lines.</p>`

})

iv. The styleUrls

You can declare component styles for its template by referencing an external file. To declare the styles for a component in a separate file, add a styleUrls property to the @Component decorator.

@Component({

  selector: ‘app-example’,

  templateUrl: ‘./example.component.html’,

  styleUrls: [‘./example.component.css’]

})

As we know, to render or display a component, we need to use the selector as follows:

<app-example></app-example>

But we can also create nested elements using the selectors. For example, we need a pair of nested components as follows:

To display this, we can use the selectors as follows:

<app-componentA>

<app-componentB></app-componentB>

</app-componentA>

Here, component A is known as parent component and component B is known as child component. This is known as nesting elements.

Quiz:

What is an Angular component?

a) A building block of an Angular application

b) A module that encapsulates the app’s logic

c) A service that handles data communication

d) A routing configuration for navigation

Which decorator is used to define an Angular component?

a) @Component

b) @Injectable

c) @Directive

d) @NgModule

How do you create a new Angular component using the Angular CLI?

a) ng create component MyComponent

b) ng generate component MyComponent

c) ng make component MyComponent

d) ng add component MyComponent

What is the purpose of the “selector” property in an Angular component?

a) It defines the component’s HTML template

b) It specifies the component’s CSS styles

c) It provides a way to reference the component in other parts of the app

d) It determines the component’s input properties

What is the purpose of the “templateUrl” property in an Angular component?

a) It defines the component’s HTML template

b) It specifies the component’s CSS styles

c) It determines the component’s input properties

d) It provides a way to reference the component in other parts of the app

What is the purpose of the styleUrls property in an Angular component?

a) It specifies the location of the component’s template file

b) It defines the CSS styles to be applied to the component

c) It lists the URLs of external libraries required by the component

d) It determines the routing configuration for the component

What is the purpose of the template in an Angular component?

a) To define the component’s HTML structure

b) To define the component’s business logic

c) To define the component’s styles

d) To define the component’s dependencies

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/4-component-creation-and-nesting/feed/ 0 198
5. Binding data, event, property, two way data binding https://edupoly.in/angular-training-tutorial/angular-basics-level1/5-binding-data-event-property-two-way-data-binding/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/5-binding-data-event-property-two-way-data-binding/#respond Mon, 13 May 2024 12:42:06 +0000 https://edupoly.in/?p=250

Data binding automatically keeps your page up-to-date based on your application’s state. You use data binding to specify things such as the source of an image, the state of a button, or data for a particular user.

Angular provides three categories of data binding according to the direction of data flow:

  1. From the source to view(Interpolation and property binding).
  2. From view to source(event binding).
  3. In a two way sequence of view to source to view(two-way data binding).

i. Interpolation

Text interpolation lets you incorporate dynamic string values into your HTML templates. Use interpolation to dynamically change what appears in an application view. Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces {{ and }} as delimiters.

To illustrate how interpolation works, consider an Angular component that contains a currentCustomer variable:

currentCustomer = ‘Maria’;

Use interpolation to display the value of this variable in the corresponding component template:

<h1>{{ currentCustomer }}</h1>

Angular replaces currentCustomer with the string value of the corresponding component property. In this case, the value is Maria.

ii. Property binding

Property binding in Angular helps you set values for properties of HTML elements or directives. Use property binding to do things such as toggle button functionality, set paths programmatically, and share values between components.

To bind to an element’s property, enclose it in square brackets, [], which identifies the property as a target property. A target property is the DOM property to which you want to assign a value. For example, the target property in the following code is the image element’s src property.

<img [src]=”itemImageUrl”>

Here, itemImageUrl represents a property present in the component class. Angular will treat the value of that property as an expression and will try to resolve or evaluate it and assign the resultant value to the src property of the img element.

iii. Event binding

Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches.

To bind to an event you use the Angular event binding syntax. This syntax consists of a target event name within parentheses to the left of an equal sign, and a quoted template statement to the right. In the following example, the target event name is click and the template statement is onSave().

<button (click)=”onSave()”>Save</button>

iv. Two-way data binding

Two-way data binding refers to sharing data between a component class and its template. If you change data in one place, it will automatically reflect at the other end. 

To start with, you need to first import the FormsModule in the AppModule so that you can use the ngModel directive.

Then you need an input field in your template which can be binded to a component property using the ngModel directive.

For example, if you change the value of the input box, then it will also update the value of the attached property in a component class. Angular’s two-way binding syntax is a combination of square brackets and parentheses, [()]. The [()] syntax combines the brackets of property binding, [], with the parentheses of event binding, (), as follows.

Quiz:

What is data binding in Angular?

a) It is a technique to establish communication between the component and its template.

b) It is a way to store data in the browser’s local storage.

c) It is a method to fetch data from an API.

d) It is a way to style HTML elements.

What is the purpose of interpolation in Angular?

a) To bind data from the component to the template.

b) To handle events in the template.

c) To create reusable components.

d) To perform validation on form inputs.

Which syntax is used for two-way data binding in Angular?

a) {{ }}

b) [ ]

c) ( )

d) [( )]

Which directive is used to bind an event in Angular?

a) ngFor

b) ngIf

c) ngModel

d) ( )

What is the purpose of event binding in Angular?

a) To bind data from the component to the template.

b) To handle events in the template.

c) To create reusable components.

d) To perform validation on form inputs.

Which syntax is used to bind a component property to an element’s attribute in Angular?

a) {{ }}

b) [ ]

c) ( )

d) [( )]

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/5-binding-data-event-property-two-way-data-binding/feed/ 0 250
6. Directives_ ngIf and ngFor https://edupoly.in/angular-training-tutorial/angular-basics-level1/6-directives_-ngif-and-ngfor/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/6-directives_-ngif-and-ngfor/#respond Mon, 13 May 2024 13:08:55 +0000 https://edupoly.in/?p=258

Angular templates are dynamic. When Angular renders them, it transforms the DOM according to the instructions given by directives. Directives are classes that add additional behavior to elements in your Angular applications. Angular has some built-in directives like NgIf and NgFor.

a. NgIf

NgIf is a structural directive that conditionally includes a template based on the value of an expression. When the value of the expression is false, Angular removes an element and its descendants from the DOM. Angular then disposes of their components, which frees up memory and resources.

To add or remove an element, bind *ngIf to a condition expression such as isValid in the following example.

<p *ngIf=”isValid”>Hello</p>

When the isValid expression returns a truthy value, NgIf adds the p element to the DOM. When the expression is falsy, NgIf removes the p element from the DOM and disposes of the component and all of its sub-components.

b. NgFor

NgFor is a structural directive that renders a template for each item in a collection which must be an iterable such as an array. You can use the NgFor directive to present a list of items.

To demonstrate the usage of ngFor, let us initialize an array in the component class as follows

export class ExampleComponent {

  courses = [‘HTML’, ‘CSS’, ‘JS’, ‘Angular’];

}

  1. Define a block of HTML that determines how Angular renders a single item.
  2. To list your items, assign the short hand let course of courses to *ngFor.

This will generate elements as follows:

<div>

   <p>HTML</p>

</div>

<div>

   <p>CSS</p>

</div>

<div>

   <p>JS</p>

</div>

<div>

   <p>Angular</p>

</div>

Quiz:

What is an Angular directive?

a) A class that adds additional behavior to elements in Angular

b) A programming language used in Angular

c) A component that handles HTTP requests

d) A feature that manages routing in Angular

Which directive is used to conditionally render elements?

a) ngIf

b) ngFor

c) ngSwitch

d) ngClass

What does the ngFor directive do?

a) Iterates over a collection and creates a template for each item

b) Conditionally renders elements based on a boolean expression

c) Adds or removes an element from the DOM

d) Updates the CSS classes of an element based on a condition

Which directive is used to handle element repetition in Angular?

a) ngRepeat

b) ngLoop

c) ngFor

d) ngIterate

Answer: c

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/6-directives_-ngif-and-ngfor/feed/ 0 258
7. Parent-child communication with @Input() https://edupoly.in/angular-training-tutorial/angular-basics-level1/7-parent-child-communication-with-input/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/7-parent-child-communication-with-input/#respond Mon, 13 May 2024 13:10:10 +0000 https://edupoly.in/?p=260

A common pattern in Angular is sharing data between a parent component and one or more child components. To implement this pattern use the @Input() decorator.

Consider the following hierarchy:

<parent-component>

  <child-component></child-component>

</parent-component>

The <parent-component> serves as the context for the <child-component>.

@Input() lets a parent component update data in the child component. 

Parent to child component communication using @Input decorator

The @Input() decorator in a child component signifies that the property can receive its value from its parent component.

To use @Input(), you must configure the parent and child.

Configuring the child component:

To use the @Input() decorator in a child component class, first import Input and then decorate the property with @Input(), as in the following example.

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

export class ChildComponent{

  @Input() childData:string = ”;

}

In this case, @Input() decorates the property childData, which has a type of string, however, @Input() properties can have any type, such as number, string, boolean, or object. The value for childData comes from the parent component.

Next, in the child component template, add the following:

<p>{{childData}}</p>

Configuring the parent component:

The next step is to bind the property in the parent component’s template. In this example, the parent component template is parent.component.html.

  1. In the parent component class, designate a value for parentData:
  2. Use the child’s selector, here <app-child>, as a directive within the parent component template.

Placing the child component in the parent component

  1. Use property binding to bind the childData property in the child to the parentData property of the parent.

<app-child [childData]=”parentData”></app-child>

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/7-parent-child-communication-with-input/feed/ 0 260
8. Services https://edupoly.in/angular-training-tutorial/angular-basics-level1/8-services/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/8-services/#respond Mon, 13 May 2024 13:12:33 +0000 https://edupoly.in/?p=262

For data or logic that isn’t associated with a specific view, and that you want to share across components, you create a service class. A service class definition is immediately preceded by the @Injectable() decorator. The decorator provides the metadata that allows other providers to be injected as dependencies into your class.

A component can delegate certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console. By defining such processing tasks in an injectable service class, you make those tasks available to any component. You can also make your application more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances.

Creating a service using CLI

Run the ng generate service <service-name> command, where <service-name> is the name of your service.

This creates the following files:

The created service file(my.service.ts) looks like this:

import { Injectable } from ‘@angular/core’;

@Injectable({

  providedIn: ‘root’,

})

export class MyService {

  constructor() { }

}

Dependency injection

When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types. For example, the constructor of MyListComponent needs MyService.

export class MyListComponent {

 constructor(private service: MyService) { }

}

We need to inject the MyService in the MyListComponent using the constructor in order to use the service for communication.

Component communication using services

Now let us see how to set up communication between components using services.

First let us create two components using the ng generate command:

ng generate component first

ng generate component second

This creates two components as follows:

Now, create a service using the ng generate command:

ng generate service my

This will create a service named MyService

import { Injectable } from ‘@angular/core’;

@Injectable({

  providedIn: ‘root’,

})

export class MyService {

  constructor() { }

}

Now let us try to send some data from the FirstComponent to the SecondComponent which we created earlier.

First, we create a property in the FirstComponent as follows:

import { Component } from ‘@angular/core’;

@Component({

  selector: ‘app-first’,

  templateUrl: ‘./first.component.html’,

  styleUrls: [‘./first.component.css’]

})

export class FirstComponent {

  data1 = “edupoly”;

}

Next, we need to send this data to the service, which can later be sent to the SecondComponent.

To use the service to store this data, we have to inject the service in the FirstComponent with the help of the constructor as follows:

import { Component } from ‘@angular/core’;

import { MyService } from ‘../my.service’;

@Component({

  selector: ‘app-first’,

  templateUrl: ‘./first.component.html’,

  styleUrls: [‘./first.component.css’]

})

export class FirstComponent {

  data1 = “edupoly”;

  constructor(private myService:MyService){

  }

}

Now, we need to create a property in the service where we will store the data from the FirstComponent.

import { Injectable } from ‘@angular/core’;

@Injectable({

  providedIn: ‘root’

})

export class MyService {

  data:any;

  constructor() { }

}

Next, let us store the data of the FirstComponent in the property of the MyService  as follows:

import { Component } from ‘@angular/core’;

import { MyService } from ‘../my.service’;

@Component({

  selector: ‘app-first’,

  templateUrl: ‘./first.component.html’,

  styleUrls: [‘./first.component.css’]

})

export class FirstComponent {

  data1 = “edupoly”;

  constructor(private myService:MyService){

    this.myService.data = this.data1;

  }

}

Now, we can access this data in our SecondComponent by accessing the service by injecting it in a similar manner as follows:

import { Component } from ‘@angular/core’;

import { MyService } from ‘../my.service’;

@Component({

  selector: ‘app-second’,

  templateUrl: ‘./second.component.html’,

  styleUrls: [‘./second.component.css’]

})

export class SecondComponent {

  data2:any;

  constructor(private myService:MyService){

    this.data2 = this.myService.data;

  }

}

The received data can be displayed in the template of SecondComponent by using interpolation.

<p>{{data2}}</p>

Quiz:

What is a service in Angular?

a. A module for organizing components

b. A class that provides a specific functionality

c. An Angular directive

d. A decorator for styling components

Which decorator is used to mark a class as an injectable service in Angular?

a. @Component

b. @Directive

c. @Injectable

d. @Service

What is dependency injection in Angular?

a. A way to inject dependencies into a component

b. A technique to create circular dependencies between components

c. A method to add external libraries to an Angular project

d. A process to eliminate the need for services in Angular

How do you inject a service into a component in Angular?

a. Using the @Inject decorator

b. Using the @Injectable decorator

c. Using the constructor of the component

d. Using the @Component decorator

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/8-services/feed/ 0 262
9. HTTP https://edupoly.in/angular-training-tutorial/angular-basics-level1/9-http/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/9-http/#respond Mon, 13 May 2024 13:13:55 +0000 https://edupoly.in/?p=264

Most front-end applications need to communicate with a server over the HTTP protocol, in order to download or upload data and access other back-end services.

The HttpClientModule in Angular is a built-in module that allows you to make HTTP requests and handle responses in your Angular applications. It provides a convenient way to communicate with servers, retrieve data, and perform CRUD (Create, Read, Update, Delete) operations over HTTP.

To use the HttpClientModule, you need to import it into your Angular module. Typically, this is done in the root module (e.g., AppModule) or a feature module where you want to use HTTP functionality. Here’s an example of importing the HttpClientModule:

import { NgModule } from ‘@angular/core’;

import { BrowserModule } from ‘@angular/platform-browser’;

import { HttpClientModule } from ‘@angular/common/http’;

@NgModule({

  imports: [

    BrowserModule,

    HttpClientModule,

  ],

  declarations: [

    AppComponent,

  ],

  bootstrap: [ AppComponent ]

})

export class AppModule {}

a. The HttpClient service

Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http. It relies on the XMLHttpRequest interface exposed by browsers. The HttpClient service class is part of the HttpClientModule which is used to send HTTP requests and receive responses from a server. It simplifies the process of making HTTP requests and handling responses by providing a set of methods and features.

b. Importing the HttpClient service class

Once the HttpClientModule is imported, you can inject the HttpClient service into your Angular components or services using dependency injection. Angular will provide an instance of the service when it is requested.

import { Injectable } from ‘@angular/core’;

import { HttpClient } from ‘@angular/common/http’;

@Injectable()

export class ConfigService {

  constructor(private http: HttpClient) { }

}

c. Using the HttpClient methods

The HttpClient service provides several methods for making different types of HTTP requests, including GET, POST, PUT, DELETE, and more. The most commonly used methods are get(), post(), put(), and delete(). The methods return observables that you can subscribe to in order to receive the response. Here are some commonly used methods:

  1. HttpClient.get()

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. 

The get() method takes an argument i.e. the endpoint URL from which to fetch the data.

this.http.get(url).subscribe(data => {

  // Handle the response

});

  1. HttpClient.post()

Apps often send data to a server with a POST request when submitting a form. The HttpClient.post() method takes a resource URL and a request body as parameters.

const body = { name: ‘John’, age: 30 };

this.http.post(url, body).subscribe(data => {

  // Handle the response

});

  1. HttpClient.put()

An app can send PUT requests using the HTTP client service. The HttpClient.put() method replaces a resource with updated data.

const body = { name: ‘John’, age: 30 };

this.http.put(`${this.heroesUrl}/${id}`, body).subscribe(data => {

  // Handle the response

});

  1. HttpClient.delete()

The application can delete a resource with the HttpClient.delete() method by passing the resource’s id in the request URL.

this.http.delete(`${this.heroesUrl}/${id}`).subscribe(data => {

  // Handle the response

});

These are the ways we can use the HTTP methods for CRUD operations. Here, we are both calling the HTTP methods as well as handling the HTTP response at the same place. This may make our component look a bit clumsy sometimes. So, it is always a good practice to separate the HTTP calls and the response handling in different places in order to make our code easily readable. In order to achieve this, we place the HTTP calls separately in a service file and handle the response in our component.

Let us consider a small example where we will make a simple HTTP GET call to receive some data. As I have explained earlier, we need to place the HTTP call in a service as follows:

import { Injectable } from ‘@angular/core’;

import {HttpClient} from ‘@angular/common/http’;

@Injectable({

  providedIn: ‘root’

})

export class MyService {

  constructor(private http:HttpClient) { }

  url = ‘https://abc.xyz’;

  getCourses(){

    return this.http.get(this.url);

  }

}

Next, we will handle the response of the GET method in our component as follows:

import { Component } from ‘@angular/core’;

import { MyService } from ‘./my.service’;

@Component({

  selector: ‘app-root’,

  templateUrl: ‘./app.component.html’,

  styleUrls: [‘./app.component.css’]

})

export class AppComponent {

  courses:any;

  constructor(private ms:MyService){

  }

  handleGetMethod(){

    this.ms.getCourses().subscribe((res:any)=>{

      this.courses = res;

    });

  }

}

Here, we are injecting the MyService and using its getCourses method which is returning an Observable. In the handleGetMethod, we are subscribing the Observable to access the response and accordingly we can handle the response as required.

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/9-http/feed/ 0 264
10.Routing https://edupoly.in/angular-training-tutorial/angular-basics-level1/10-routing/ https://edupoly.in/angular-training-tutorial/angular-basics-level1/10-routing/#respond Mon, 13 May 2024 13:14:52 +0000 https://edupoly.in/?p=266

In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. Routing in Angular refers to the mechanism used to navigate between different views or pages in a single-page application (SPA). It allows users to interact with different components of the application without the need for a full page reload. Angular provides a powerful routing module that enables developers to define and handle routes in a declarative manner.

To handle the navigation from one view to the next, you use the Angular Router. The Router enables navigation by interpreting a browser URL as an instruction to change the view.

The Router module

Angular’s routing is managed by the RouterModule, which is part of the @angular/router package. It is a module that adds directives and providers for in-app navigation among views defined in an application. Use the Angular Router service of the RouterModule to declaratively specify application states and manage state transitions.

Importing the Router module

If an application is created with the –routing flag using the CLI as shown below, it automatically creates a routing module called AppRoutingModule.

ng new my-project –routing

The AppRoutingModule needs to be imported into the AppModule. 

The RouterModule and Routes need to be imported into the AppRoutingModule. The Angular CLI performs this step automatically. The CLI also sets up a Routes array for your routes and configures the imports and exports arrays for @NgModule(). 

import { NgModule } from ‘@angular/core’;

import { Routes, RouterModule } from ‘@angular/router’;

const routes: Routes = [];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

Configuration

To configure the routing, you need to define the routes in the Routes array.

Each route in this array is a JavaScript object that contains two properties. The first property, path, defines the URL path for the route. The second property, component, defines the component Angular should use for the corresponding path.

const routes: Routes = [

  { path: ‘first-component’, component: FirstComponent },

  { path: ‘second-component’, component: SecondComponent },

];

Now that you have defined your routes, you can add them to your application. First, add links to the two components. Assign the anchor tag that you want to add the route to the routerLink attribute. Set the value of the attribute to the component to show when a user clicks on each link. Next, update your component template to include <router-outlet>. This element informs Angular to update the application view with the component for the selected route.

<h1>Angular Router App</h1>

<nav>

  <ul>

    <li><a routerLink=”/first-component”>First Component</a></li>

    <li><a routerLink=”/second-component”>Second Component</a></li>

  </ul>

</nav>

<router-outlet></router-outlet>

Child routes

As your application grows more complex, you may want to create routes that are relative to a component other than your root component. These types of nested routes are called child routes. This means you’re adding a second <router-outlet> to your app, because it is in addition to the <router-outlet> in AppComponent.

In this example, there are two additional child components, child-a, and child-b. Here, FirstComponent has its own <nav> and a second <router-outlet> in addition to the one in AppComponent.

<h2>First Component</h2>

<nav>

  <ul>

    <li><a routerLink=”child-a”>Child A</a></li>

    <li><a routerLink=”child-b”>Child B</a></li>

  </ul>

</nav>

<router-outlet></router-outlet>

A child route is like any other route, in that it needs both a path and a component. The one difference is that you place child routes in a children array within the parent route.

const routes: Routes = [

  {

    path: ‘first-component’,

    component: FirstComponent,

    children: [

      {

        path: ‘child-a’,

        component: ChildAComponent,

      },

      {

        path: ‘child-b’,

        component: ChildBComponent,

      },

    ],

  },

];

]]>
https://edupoly.in/angular-training-tutorial/angular-basics-level1/10-routing/feed/ 0 266