Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE.eu :: What is Angular Dependency Injection?

clock September 15, 2023 09:16 by author Peter

Dependency Injection (DI) is a core Angular design pattern that aids in the management of dependencies as well as the flow of data and services inside an application. It allows for loose coupling between components, which makes your code more modular, maintainable, and testable.

Why are We using Dependency Injection and without dependency using what problem in real-life example?

Real-Life Example: A Car Factory
Imagine you're managing a car manufacturing factory. In your factory, you have various assembly lines responsible for different parts of the car, such as the engine, chassis, electronics, and tires. Each assembly line relies on specific tools and materials to complete its tasks.

Now, think about how you might manage these dependencies in your car factory.

  • No Dependency Injection (DI): Without dependency injection, each assembly line would have to manage its own dependencies. For example:
    • The engine assembly line would need to procure and maintain its own inventory of engines, tools, and spare parts.
    • The electronics assembly line would need to do the same for electronic components.
    • The tire assembly line would need its own inventory of tires and tire-related equipment.
  • This approach would lead to several problems.
    • Duplication of effort: Each assembly line would have to manage its dependencies separately, resulting in duplicated resources and potential inconsistencies.
    • Maintenance nightmare: If a tool or part needed to be updated or replaced, every assembly line using that tool or part would need to be individually updated.
    • Lack of flexibility: Changing or upgrading components or tools across multiple assembly lines would be challenging and error-prone.
  • Dependency Injection (DI) in the Car Factory: Now, let's introduce dependency injection into the car factory.
    • You create a central inventory management system (akin to Angular's dependency injection container).
    • Each assembly line declares its dependencies on the central system.
    • When an assembly line needs an engine, electronics, or tires, it requests them from the central inventory system (dependency injection).
    • The central system ensures that each assembly line gets the correct parts and tools.
  • Benefits of this approach.
    • Centralized control: You have a single point of control for managing all dependencies, making it easier to update, replace, or upgrade tools and components.
    • Consistency: All assembly lines use the same source for their dependencies, ensuring consistency and reducing errors.
    • Flexibility: You can easily switch out components or tools across the factory by updating the central inventory system.

In Angular
In Angular applications, components, services, and other parts of the application often have dependencies. Dependency injection works similarly to the car factory example:

Angular's DI container manages dependencies and ensures that each component or service gets the correct instances of the dependencies it needs.
This promotes modularity, maintainability, and testability in your Angular application, as you can easily swap out components or services without modifying each dependent part individually.

So, in both the car factory and Angular, dependency injection simplifies management, promotes consistency, and makes it easier to adapt to changes in the dependencies, ultimately leading to more efficient and maintainable systems.

In Angular How to Achieve!
In Angular, dependency injection is achieved through the built-in dependency injection system. Here's how you can achieve dependency injection in Angular.

Step 1. Create Service in your Application
First, you need to create a service that provides the functionality or data you want to inject into other components. Services are classes annotated with the @Injectable decorator. What are the services using this Application? All the functionalities of the service to implemented in the servicefile.

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})

export class EmployeeService {

  EmpApi= environment.EmployeeAPI;
  constructor(private http:HttpClient) { }

  GetEmployeeList(){
    return this.http.get(this.EmpApi+'Employee/List');
  }
}

Step 2. Inject Service into Components
Next, you inject the service into the components or other services where you need it. You can do this by including the service as a parameter in the constructor of the component or service that requires it. Angular's dependency injection system will take care of providing an instance of the service automatically.


import { Component, OnInit } from '@angular/core';
import { EmployeeService } from 'src/app/Service/employee.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({

  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']

})

export class EmployeeListComponent implements OnInit  {

  collectionData: any;
  iframeSrc!: string;
  constructor( private empService:EmployeeService,private route: Router){

  }

  ngOnInit(): void {
   this.empList();
  }

  empList(){
    return this.empService.GetEmployeeList().subscribe((res:any)=>{
      this.collectionData=res.data;

    })
  }
}

Conclusion
That's it! With these steps, you've achieved dependency injection in Angular. The Angular framework will take care of creating and managing the service instances and injecting them where needed, promoting modularity and maintainability in your application.



AngularJS Hosting Europe - HostForLIFE.eu :: View Encapsulation in Angular

clock August 29, 2023 08:16 by author Peter

Angular is a popular and capable framework for developing online apps. View Encapsulation is one of its core characteristics, and it is essential for regulating component styling and behavior. In this article, we'll look into View Encapsulation in Angular, why it's important, and how it works.

What exactly is View Encapsulation?
View Encapsulation is a key notion in Angular that helps to keep styles and behaviors isolated for specific components. It ensures that styles defined in one component do not have an impact on other components in the application. This encapsulation protects your code from unforeseen side effects and encourages modularity and reusability.

View Encapsulation Types
View Encapsulation in Angular comes in three flavors.
Emulated (Default): This is Angular's default behavior. The styles defined in a component's CSS are scoped to that component's view in Emulated View Encapsulation. Angular accomplishes this by adding unique properties to the component's HTML elements. To guarantee that the styles only apply to the component's view, these characteristics are utilized as selectors in the resulting CSS.

/* Component CSS */ .my-component { color: red; }

<!-- Generated HTML -->
<div _ngcontent-c1 class="my-component">Hello, World!</div>

Shadow DOM: Angular uses the browser's native Shadow DOM encapsulation in this mode. Each component is assigned its own Shadow DOM, which separates the component's styling and DOM structure from the rest of the page. This approach offers a high level of encapsulation, but it may be incompatible with outdated browsers.
None: When you select None, Angular does not apply any encapsulation, and the styles defined in a component's CSS file influence the entire application. While this mode is useful in some situations, it should be utilized with caution to avoid unwanted consequences.

How Do I Select the Best Encapsulation Mode?
Choosing the Correct View Encapsulation mode is determined by the requirements and goals of your project:
Emulated: This is the preferred mode for most applications. It strikes a decent compromise between encapsulation and compatibility, and it works effectively in most cases.
Shadow DOM: Use this option if you need a greater level of encapsulation and are developing a modern application for browsers that support Shadow DOM.
None: Use None only when absolutely necessary, such as for global styles that must apply to the entire application. When utilizing this option, be cautious because it can cause style conflicts and maintenance issues.

How Do You Define View Encapsulation?
The View Encapsulation mode for a component can be specified using the encapsulation attribute in the component's metadata. As an example:

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
  encapsulation: ViewEncapsulation.Emulated
})
export class MyComponent {}

Conclusion
View Encapsulation is an important feature of Angular that helps maintain clean, modular, and reusable code by segregating component styles and actions. It gives developers the freedom to select the level of encapsulation that best meets the needs of their project. Whether you use Emulated, Shadow DOM, or None, understanding and skillfully employing View Encapsulation will help your Angular applications succeed by fostering clean and maintainable code.

Good luck with your studies :)



AngularJS Hosting Europe - HostForLIFE :: Data Sharing from a Child to a Parent in Angular

clock August 22, 2023 12:06 by author Peter

The @Output decorator is used in this article to share data from child to parent components in Angular. We'll go through the fundamental ideas underlying this technique, show how it works in practice using examples, and explain its benefits in terms of code organization, reusability, and maintainability. By the end of this article, you'll have a solid grasp of how to use the @Output decorator to add efficient data flow methods to your Angular apps.

Understanding Interaction of Components
Components are the building blocks of the user interface in Angular apps. They can be organized hierarchically, with parent components encapsulating child components.

These components frequently need to communicate with one another, transmitting data back and forth. While data sharing between parent and child components is very simple using input attributes, data sharing between child and parent components requires a different technique.

The @Output Decorator is a feature of Angular that allows communication between child and parent components to be more efficient. To emit custom events from the child component, it is used in conjunction with Angular's EventEmitter class. The parent component is aware of these events and can respond appropriately.
Step-by-Step Instructions

Let's go over how to use @Output in Angular to implement data sharing from child to parent components step by step.

Step 1: Make a Child Component

Create the child component first.
ng generate component child

In the child component HTML file (child.component.html), include a button to trigger the data emission.
<button (click)="sendData()">Send Data</button>

In the child component TypeScript file (child.component.ts), import the necessary modules, and create an @Output property and an instance of EventEmitter to emit the data.
import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent {
  @Output() dataEvent = new EventEmitter<string>();

  sendData() {
    this.dataEvent.emit('Hello from child!');
  }
}


Step 2. Use the Child Component in the Parent

Now, use the child component in the parent component HTML file (parent.component.html).
<app-child (dataEvent)="receiveData($event)"></app-child>
<div>{{ receivedData }}</div>


In the parent component TypeScript file (parent.component.ts), define the method to handle the emitted event.
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
  receivedData: string = '';

  receiveData(data: string) {
    this.receivedData = data;
  }
}

In conjunction with EventEmitter, Angular's @Output decorator provides a strong mechanism for passing data from child to parent components. You can enable effective communication and interaction between different portions of your program by broadcasting custom events from child components. By fostering a clear separation of concerns, this strategy improves the modularity and maintainability of your system.

This pattern remains a core strategy for component interaction in Angular. Developers may create more dynamic and responsive user interfaces in their Angular applications by mastering the art of exchanging data with @Output.



AngularJS Hosting Europe - HostForLIFE :: Using @Input(), Angular Allows Data to be Shared from Parent to Child Components

clock August 16, 2023 08:08 by author Peter

In this post, we will look at how to use the @Input() decorator in Angular to share data from a parent component to a child component.

Recognizing the @Input() Decorator
The @Input() decorator allows you to transmit data from a parent component to a child component in Angular. It effectively establishes an input property on the child component that may be tied to a value in the template of the parent component. When the value of the input property in the parent component changes, the child component is automatically updated with the new value.

Configuring the Parent Component
Let's begin with a simple example. Consider the following scenario: we have a parent component that displays a user's name, and we wish to pass this name to a child component for display.

Using the Angular CLI, create a new parent component:
ng generate component parent

Open the parent.component.ts file and add the @Input() decorator to the following property:
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <h1>Hello, {{ userName }}!</h1>
    <app-child [inputName]="userName"></app-child>
  `,
})
export class ParentComponent {
  userName = 'Tahir Ansari';
}


Creating the Child Component

Now, let's create the child component that will receive and display the user's name.

Generate a child component using the Angular CLI:
ng generate component child

In the child.component.ts file, use the @Input() decorator to define an input property:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <p>Received name from parent: {{ receivedName }}</p>
  `,
})
export class ChildComponent {
  @Input() inputName: string;

  get receivedName() {
    return this.inputName;
  }
}


Wiring Up the Module
ensure that you declare both the parent and child components in your module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';

@NgModule({
  imports: [BrowserModule],
  declarations: [ParentComponent, ChildComponent],
  bootstrap: [ParentComponent],
})
export class AppModule {}


Conclusion
In this article, we've seen how to pass data from a parent component to a child component in Angular using the @Input() decorator. This feature allows for seamless communication between components and enables dynamic updates whenever the data in the parent component changes.

Angular's component-based architecture, combined with features like @Input(), empowers developers to build modular and maintainable applications by promoting the separation of concerns and reusability of components.



AngularJS Hosting Europe - HostForLIFE.eu :: HTTP Interceptors in Angular

clock August 14, 2023 08:28 by author Peter

In this tutorial, we will go through the fundamentals of HTTP Interceptors in Angular and provide some examples using Angular 15.


What exactly is Angular?
Angular is a popular open-source JavaScript web application framework. It was created by Google and is presently maintained by the Google Angular Team. Angular enables developers to create dynamic, single-page applications (SPAs) and offers a disciplined way to developing complicated online apps.

What exactly is an HTTP Interceptor?

HTTP Interceptors are a type of notion in web development and server-side programming that is commonly connected with web frameworks and tools.

These interceptors enable developers to intercept and manage HTTP requests and answers at the application level.

  • They can be used to perform various tasks related to HTTP requests and responses, such as adding headers, handling errors, modifying the request or response data, logging, authentication, etc.
  • HttpInterceptor defines a single method called intercept, which takes two parameters: the HttpRequest and the HttpHandler.

Benefits of HTTP Interceptors
Following are some of the key benefits of using HTTP Interceptors in Angular:
Testability and reusability: Interceptors are easy to test in isolation, allowing you to ensure that each interceptor behaves correctly
Centralized code for cross-cutting concerns: HTTP Interceptors allow you to define logic for common tasks, such as authentication, logging, error handling, or adding headers, in a centralized location.
Global application-level modifications: Interceptors operate globally, intercepting all HTTP requests and responses made by the Angular application. This means you can apply changes or perform actions consistently across multiple API calls without having to modify each individual request or response manually.

Error handling and logging: Interceptors can be utilized to handle errors globally, providing a consistent approach to error reporting and handling throughout the application.

Caching and request/response manipulation: HTTP Interceptors can be leveraged to implement caching mechanisms, reducing redundant requests and optimizing the application’s performance.

Separation of concerns: By using HTTP Interceptors, you can keep concerns related to data fetching and communication (HTTP) separate from the business logic of your components and services.

Security and authentication: Interceptors are commonly used for adding authorization headers or authentication tokens to outgoing requests. This ensures that the user’s authentication status is automatically included in API calls without the need to explicitly set headers in every request.

Easy integration with third-party libraries: Interceptors can be used to integrate with third-party libraries or APIs seamlessly. For example, you can apply a specific format to API responses that are expected by a charting library or a data visualization tool.

Practical Implementation

Let’s start with practical implementation; for that, we need to create a new Angular application using the following command.
ng new angular-http-interceptor-demo

Now, we are going to create different interceptors one-by-one with the help of angular.

1. Logging Interceptor

In Angular, logging interceptors can be used for audit log purposes. If we want to log different incoming and outgoing requests with request and response objects, we can do so with the help of a logging interceptor.

Step 1
Create a new logging interceptor with the help of the following command.
ng g interceptor logging

This command will create the logging interface with a default implementation. So, modify the same as I have shown below.
import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Observable, tap } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    console.log('Outgoing HTTP request', request);
    return next.handle(request).pipe(
      tap((event: HttpEvent<any>) => {
        console.log('Incoming HTTP response', event);
      })
    );
  }
}


Here, we import the necessary modules and classes from Angular’s HTTP package.

The HttpInterceptor interface allows us to create our custom interceptor, and HttpRequest, HttpHandler, and HttpEvent are classes used for handling HTTP requests and responses.

We also import Observable and Tap from the RxJS library, which is used for handling asynchronous operations.
We call next.handle(request) to pass the request to the next interceptor in the chain or the backend server.
Then, we use the pipe method along with the tap operator to intercept the incoming response.
The tap operator allows us to execute a side effect (in this case, log the response) without modifying the response itself.

Step 2
Provide an interceptor in the app module.
import { LoggingInterceptor  } from './interceptors/logging.interceptor'

 providers: [
    {
      provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true
    }
  ]

In the AppModule, we provide the LoggingInterceptor class as an interceptor using the HTTP_INTERCEPTORS token. The multi: true option ensures that the interceptor is appended to the existing array of interceptors rather than replacing them.

When you make an HTTP request, it will get logged with the following request and response.

In a real-time scenario, you can log this response in a third-party service as per need and requirement.

2. Adding Headers to Requests

In Angular, we can modify HTTP Requests and add some extra value to the request header with the help of an interceptor.

Step 1
Create a new header interceptor with the help of the following command.
ng g interceptor headers

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class HeadersInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    console.log(request)
    const GUID = 'f4179b26-21ac-432c-bcd8-cb4bc6e50981'
    const modifiedRequest = request.clone({
      setHeaders:{
        GUID
      }
    })
    return next.handle(modifiedRequest);
  }
}


Here we first hardcode one GUID that we are going to set inside the header. So, first, we need to clone that HTTP request and use the set headers property to set the value in the request header.

Step 2
Provide an interceptor in the app module.
import { HeadersInterceptor  } from './interceptors/headers.interceptor'

providers: [
    {
      provide: HTTP_INTERCEPTORS, useClass: HeadersInterceptor, multi: true
    }
  ]

In the AppModule, we provide the HeadersInterceptor class as an interceptor using the HTTP_INTERCEPTORS token. The multi: true option ensures that the interceptor is appended to the existing array of interceptors rather than replacing them.

In a real-time scenario, you can use these header values for further processing, like validating requests, and in many other cases.

3. Error Handling Interceptor
In Angular, The Error interceptor is an HTTP interceptor that allows you to handle HTTP errors globally within your application.
When you make HTTP requests to a server, there might be scenarios where the server responds with an error status code, such as 404 or 500.
Handling these errors in each individual HTTP request can be tedious and repetitive.

The Error Interceptor helps you centralize the error-handling logic and provides a consistent way to manage errors across your application.

Step 1
Create a new error interceptor with the help of the following command.
ng g interceptor error

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        // Handle the error here
        console.error('error occurred:', error);
        //throw error as per requirement
        return throwError(error);
      })
    );
  }
}


Inside the intercept() method, you can use the catchError operator from RxJS to catch any errors that occur during the HTTP request or response handling.
This operator allows you to intercept the error, handle it as needed, and optionally re-throw the error to propagate it further up the observable chain.

Step 2
Provide interceptor in the app module:
import { ErrorInterceptor } from './interceptors/error.interceptor';

  providers: [
    {
      provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true
    }
  ]

In the AppModule, we provide the HeadersInterceptor class as an interceptor using the HTTP_INTERCEPTORS token. The multi: true option ensures that the interceptor is appended to the existing array of interceptors rather than replacing them.

4. Authentication Interceptor
In Angular, an authentication interceptor can be used to add authentication tokens or headers to every outgoing HTTP request. This is helpful when you need to ensure that all API requests are authenticated.

Step 1
Create a new authentication interceptor with the help of the following command.
ng g interceptor auth

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
//import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(/*private authService: AuthService*/) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const authToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpheWRlZXAgUGF0aWwiLCJpYXQiOjE1MTYyMzkwMjJ9.yt3EOXf60R62Mef2oFpbFh2ihkP5qZ4fM8bjVnF8YhA";//his.authService.getToken();

    if (authToken) {
      // Clone the request and attach the token
      const authReq = req.clone({
        setHeaders: {
          Authorization: `Bearer ${authToken}`
        }
      });

      return next.handle(authReq);
    }

    // If there is no token, pass the original request
    return next.handle(req);
  }
}


Here we first hardcode one token that we are going to set inside the header. So, for that, first, we need to clone that HTTP request and need to use the set headers property to set the value in the request header.

Step 2
Provide an interceptor in the app module:
import { AuthInterceptor } from './interceptors/auth.interceptor';

  providers: [
    {
      provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true
    }


In the AppModule, we provide the HeadersInterceptor class as an interceptor using the HTTP_INTERCEPTORS token. The multi: true option ensures that the interceptor is appended to the existing array of interceptors rather than replacing them.

When you make an HTTP request, it will set a token inside the header, as shown below.


As you can see, we set one bearer token that you can use for further processing as per requirement.



AngularJS Hosting Europe - HostForLIFE.eu :: A Fresh Method for Creating Angular Applications

clock August 4, 2023 09:02 by author Peter

The Angular team has been primarily focused on the removal of the Angular Framework legacy code block and rendering pipeline in recent releases. These actions are primarily carried out with the goal of improving performance. As part of this endeavor, the Angular team developed a new idea of defining the component, Standalone Component, in Angular 14. We can easily develop any application without using the NgModel with the aid of this idea. This technique allows developers to complete Angular application development considerably faster, and most significantly, they do not need to grasp or consider the concept of NgModule within the application at all.


As a result, in this article, we will go through the concept of a Standalone Component in any angular application.

An Overview of Standalone Component
From Angular 14 onwards, the angular team introduced the concept of the Standalone component. The standalone component is nothing but a simple component that will not be a part of any Angular module. Before Angular 14, whenever we define any component in the Angular application, we need to first declare that component within the Angular module declaration array objects. If we forgot to do that task, then the Angular compiler throws the error. But, from Angular 14 onwards, these steps are not mandatory. Because, now, we can create any component which can not be a part of any component. And that’s why it is called a Standalone component. Just like standalone components, we can also create pipes and directives as well as Standalone. This type of standalone component can be used anywhere in the application like -

  • Within any module-based component
  • Within any other Standalone component as a child component
  • Within route
  • Can use as a lady-loading component.

In Angular 14, this standalone component concept is released as a part of the developer preview. Now, in the latest version of Angular, i.e. Angular 16, we can use the Standalone Component in full swing with full work support for everything like HttpClient, Router, Angular Element, and many more.

Benefits of using a Standalone Component

As a developer, when we plan to start development work for any Angular-based application now, then we first need to decide whether we will use the legacy NgModule-based application or we will need to use the Standalone component-based architecture. So, before making this decision, we first need to understand the benefits of using a Standalone component. Some of the key benefits which we can achieve by using standalone components are as follows -

  • One of the major reasons for the Standalone component is Reusability. We can use this type of component throughout the application event in different applications. In this way, we can save development time and can reduce the chances of code duplication.
  • As the Standalone component is independent and does not dependent on any modules, so, we can perform unit testing of this component very easily.
  • In the Standalone component, we can perform encapsulation in the concept of the component’s styles and templates. It reduces interference with different components and helps us to maintain a clean codebase.
  • The concept of the Standalone component encourages us to follow modular development. We can break the large application into smaller and manageable modules and can develop those parts then.
  • Another reason for using a standalone component is the isolated state of the component. It means every standalone component can maintain its state, which is isolated from the other parts of the application.

Create An Angular Application as a Standalone
Now, in this section, we will discuss how we can create an Angular application as a Standalone component based on using the Angular CLI command. So, when we want to create any angular application as a Standalone, then we just need to add the --standalone prefix at the end of the Angular CLI command. Same logic we can use also while we create the Standalone component, directives, or pipes.
ng new angular-standalone-component-demo --standalone

Once the application is created, then it will create the project structure as below.

If we notice, we can find that in the create application structure, there is no app.module.ts file. It is because we already created this application as a standalone application. Now, if we open the app.component.ts file, we can find out the below code -
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-standalone-component-demo';
}

In the above example, we can see that standalone attribute under the @Component metadata, which indicates that this component will act as a standalone component. As it is a standalone component, so, we don’t have any NgModule for bootstrapping the component. Now, in the case of a Standalone application, one Standalone component will be treated as a root component and that component we need to bootstrap within the main.ts file as below -

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console. Error(err));

Create and Use a Standalone Component

Now, we have already created the Angular Standalone component-based application. In this demonstration, we will create one basic employee list which will display the employee list and also, and we can add the employee data to that list. For this purpose, we first create an employee list component that will display the list of employees. In this demo, whatever component we will create, all components will be a standalone components. Once we will create that component, the output will be as below

 



AngularJS Hosting Europe - HostForLIFE.eu :: Feature Module with Lazy Loading in Angular

clock July 25, 2023 07:29 by author Peter

In this article, we are going to discuss feature modules in Angular and lazy load them with the help of one practical example.

What is Angular?
Angular is a popular open-source JavaScript framework for building web applications. It was developed by Google and is currently maintained by the Angular Team at Google. Angular allows developers to create dynamic, single-page applications (SPAs) and provides a structured approach to building complex web applications.

What is a Module?
In programming, a module is a self-contained unit of code that performs a specific task or provides a set of related functions. It is a way of organizing and managing code in a modular and reusable manner.

A module can be a separate file or a collection of files that contain functions, classes, variables, or other code components. It encapsulates a specific set of functionalities, making it easier to understand, test, and maintain code.

Feature Module in Angular

In Angular, a feature module is a way to organize and encapsulate a specific set of features and functionality within an application.

It contains a group of related components, directives, services, and a few other files. It helps us maintain and manage the application codebase.

For example, Suppose we have an online shopping application that contains feature modules like user registration, products, cart, and many more with its services, directives, components, and routing-related configuration.
Benefits of Feature Module

Here are some key benefits of feature modules in Angular:

  • Encapsulation: Feature modules encapsulate related components, directives, services, and other code files within a specific feature or functionality. This encapsulation provides a clear boundary and separation of concerns, making it easier to understand and maintain code.
  • Code Organization: Feature modules help organize your codebase by grouping related code files together. This organization enhances code readability and allows developers to navigate the codebase more efficiently.
  • Code Reusability: Feature modules can be reused across multiple applications or within the same application. This reusability promotes modular and scalable development by allowing you to extract and reuse modules with specific functionalities.
  • Lazy Loading: The lazy loading feature allows you to load feature modules on-demand, improving the initial load time and performance of your application. Lazy loading ensures that only the necessary modules are loaded when navigating to specific routes, reducing the initial bundle size and optimizing the user experience.
  • Dependency Management: Feature modules in Angular have their own set of dependencies and can manage their own imports and exports. This helps in managing dependencies and prevents naming conflicts with other modules in your application.
  • Clear Interfaces: Feature modules define clear interfaces through exports, providing a way to communicate with other parts of the application. By exporting specific components, directives, or services, other modules can make use of them and interact with the features provided by the module.
  • Testing and Debugging: Feature modules enhance testability and debugging capabilities. By encapsulating related code files, it becomes easier to write unit tests specific to a module’s functionalities and isolate any issues or bugs within that module.

Lazy Loading
Lazy loading is a technique in Angular that allows you to load modules asynchronously and on-demand when they are needed. It is a powerful feature that helps improve the initial loading time of your application by loading only the necessary code for the current route instead of loading the entire application upfront.

Feature Module Example

Step 1. Install NodeJS: https://nodejs.org/en/download
Step 2. Install Angular CLI using the following command:

npm install -g @angular/cli

Step 3. Verify NodeJS and Angular CLI are installed or not using the following commands:
node –version
ng version

Step 4. Create a new Angular Application.
ng new angular-modules-demo

Step 5. Open the Angular application in one of the editors, like VS Code, and install the bootstrap with the help of the following command:
npm install bootstrap

next, add the bootstrap script inside the angular.json file inside the scripts and styles section
"styles": [
  "src/styles.css",
  "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
  "./node_modules/bootstrap/dist/js/bootstrap.min.js"
]

Step 6. Create the “FirstModule” feature module.
Navigate into the project directory:
cd angular-modules-demo

Next, create the “FirstModule” feature module by running the following command:
ng generate module modules/first-module –routing

This will generate a new module named FirstModule under the modules directory, along with a routing module named first-module-routing.module.ts specific to this module.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { FirstModuleRoutingModule } from './first-module-routing.module';
import { FirstModuleComponent } from './first-module.component';

@NgModule({
  declarations: [
    FirstModuleComponent
  ],
  imports: [
    CommonModule,
    FirstModuleRoutingModule
  ]
})
export class FirstModuleModule { }

Step 7. Create the default component for FirstModule.
Generate the default component for “FirstModule” by running the following command:
ng generate component modules/first-module/first-module-component

This will create a new component named FirstModuletComponent within the first module.
import { Component } from '@angular/core';

@Component({
  selector: 'app-first-module',
  templateUrl: './first-module.component.html',
  styleUrls: ['./first-module.component.css']
})
export class FirstModuleComponent {

}

Step 8. Configure the routing for FirstModule.
Open the first-module-routing.module.ts file under the modules/first-module directory and modify it as follows:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FirstModuleComponent } from './first-module.component';

const routes: Routes = [{ path: '', component: FirstModuleComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class FirstModuleRoutingModule { }

Step 9. Create the “SecondModule” feature module

Create the “SecondModule” feature module by running the following command:
ng generate module modules/second-module –routing

This will generate a new module named SecondModule under the modules directory, along with a routing module named second-module-routing.module.ts specific to this module.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SecondModuleRoutingModule } from './second-module-routing.module';
import { SecondModuleComponent } from './second-module.component';

@NgModule({
  declarations: [
    SecondModuleComponent
  ],
  imports: [
    CommonModule,
    SecondModuleRoutingModule
  ]
})
export class SecondModuleModule { }


Step 10. Create the default component for SecondModule.
Generate the default component for “SecondModule” by running the following command:
ng generate component modules/second-module/second-module-component

This will create a new component named SecondModuleComponent within the second module.
import { Component } from '@angular/core';

@Component({
  selector: 'app-second-module',
  templateUrl: './second-module.component.html',
  styleUrls: ['./second-module.component.css']
})
export class SecondModuleComponent {

}

Step 11. Configure the routing for the second module.
Open the second-module-routing.module.ts file under the modules/second-module directory and modify it as follows:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SecondModuleComponent } from './second-module.component';

const routes: Routes = [{ path: '', component: SecondModuleComponent }];


@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class SecondModuleRoutingModule { }


Step 12. Update the App Routing
Open the app-routing.module.ts file under the src/app directory and modify it as follows:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
 { path: 'first-module', loadChildren: () => import('./modules/first-module/first-module.module').then(m => m.FirstModuleModule) },
 { path: 'second-module', loadChildren: () => import('./modules/second-module/second-module.module').then(m => m.SecondModuleModule) },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


Here we use lazy loading in this example to navigate features modules based on navigations.

To implement lazy loading in Angular, follow these steps:
Open the main app routing module, app-routing.module.ts, and update the routes to use the loadChildren property instead of the component property for the routes that you want to lazy load. For example:
const routes: Routes = [
 { path: 'first-module', loadChildren: () => import('./modules/first-module/first-module.module').then(m => m.FirstModuleModule) },
 { path: 'second-module', loadChildren: () => import('./modules/second-module/second-module.module').then(m => m.SecondModuleModule) },
];


By using lazy loading, you can split your application into smaller, more manageable chunks, improving performance by loading modules only when they are required. This approach is particularly useful for larger applications or when you have sections of your application that are accessed less frequently.

Lazy-loaded modules are loaded asynchronously and cached by the Angular router, so subsequent visits to the same route will load the module from the cache instead of making a new request to the server.

Step 13. Update the app.component.html file.

<button type="button" class="btn btn-primary" routerLink="first-module">First Module</button>
<button type="button" class="btn btn-secondary" routerLink="second-module">Second Module</button>
<router-outlet></router-outlet>

Here we used bootstrap buttons with a router link for navigation purposes and, at the bottom, a router outlet to render different components of the feature module based on navigation.

Step 14. Finally, start the development server by running the following command:
ng serve

Navigate to http://localhost:4200 in your web browser, and you should see the Angular Modules Demo App with two navigation links: “First Module” and “Second Module.” Clicking on each link will lazily load and display the corresponding module’s component.

When we navigate the feature module, only its corresponding files will get loaded because we are lazy to load them with load children, as shown in the above image under the application console. Also, it improves performance when we have a big project with different complex modules.

Step 1. we need an Employee interface to define the properties of the employee objects as below. For this, we add one new file called employee.ts and add the below code there –

export interface EmployeeInfo
{
    emp_id : number;
    emp_code : string;
    emp_name : string;
    emp_mobile : number;
    emp_email : string;
}


Step 2. Now, add a new file called app.employee.service.ts and add the below code –
import { EmployeeInfo } from './employee';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class EmloyeeService {
  public employeeList: EmployeeInfo[] = [];

  ngOnInit(){
    this.employeeList = [
      { "emp_id": 1, "emp_name": "Roger Smith", "emp_code" : "ET0002334", "emp_mobile" : 9830098300, "emp_email": "[email protected]"},
      { "emp_id": 2, "emp_name": "Alex Bob", "emp_code" : "ET0002992", "emp_mobile" : 9830198301, "emp_email" : "[email protected]"},
      { "emp_id": 3, "emp_name": "Stephen Ken", "emp_code" : "ET0001675", "emp_mobile" : 88830098312, "emp_email" : "[email protected]"},
      ];
  }

  getEmployeeList()  {
    if (this.employeeList.length == 0 )
        this.ngOnInit();
    return this.employeeList;
  }

  initializeData(){
    this.getEmployeeList();
  }

  getEmployee(id : number){
    return this.employeeList.find(e=>e.emp_id == id);
  }

  addEmployeeInfo(emloyee : EmployeeInfo){
    this.employeeList.push(emloyee);
  }
}

Step 3. Now, add a new standalone component called app.employee.index.ts and add the below code –
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';

import { EmployeeInfo } from './employee';
import { EmloyeeService } from './app.employee.service';

@Component({
  selector: 'app-employee-index',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './app.employee.index.html'
})
export class EmployeeIndexComponent implements OnInit {
  public employeeList : EmployeeInfo[] = [] ;

  constructor(
    private _employeeService : EmloyeeService,
    private _route: Router) {

  }

  ngOnInit(){
    this.employeeList = this._employeeService.getEmployeeList();
  }

  navigateUrl(path:string, id:number){
    this._route.navigate([path, id]);
  }
}

Step 4. Now, open the HTML file called app.employee.index.html and add the below code –
<div class="container-fluid">
    <div class="row">

        <h2>Employee Records</h2>
        <div style="position: relative; width: fit-content; float: right;" class="text-right">
            <a class="btn btn-primary" href="/employee-add" role="button">Add Employee</a>
        </div>
        <div class="table-responsive">
            <table class="table table-striped table-sm">
                <thead>
                    <tr>
                        <th scope="col">S.No</th>
                        <th scope="col">Employee Code</th>
                        <th scope="col">Employee Name</th>
                        <th scope="col">Mobile No</th>
                        <th scope="col">Email Id</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor='let emp_data of employeeList'>
                        <td>{{emp_data.emp_id}}</td>
                        <td>{{emp_data.emp_code}}</td>
                        <td>{{emp_data.emp_name}}</td>
                        <td>{{emp_data.emp_mobile}}</td>
                        <td>{{emp_data.emp_email}}</td>
                        <td>
                            <button type="button" class="btn btn-info" (click)="navigateUrl('/employee-view', emp_data.emp_id)">Info</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>


Step 5. Now, open the app.component.ts file and import the EmployeeIndexComponent within that component imports array objects.
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { provideRouter, RouterOutlet } from '@angular/router';
import { EmployeeIndexComponent } from './employees/app.employee.index';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, EmployeeIndexComponent],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular 16 Application - Standalone App Demo';

}


Routing with Standalone Component
Now, in the above employee index component, we create two buttons – Add Employee and another button for View Employee details. By using these two buttons, we will navigate to the related component with the help of the routes. Now, we will define how we can define routes in the application.

Step 1. Now, add another standalone component called app.employee.view.ts file and add the following code –
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';

import { EmployeeInfo } from './employee';
import { EmloyeeService } from './app.employee.service';
import { last } from 'rxjs';

@Component({
  selector: 'app-employee-add',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './app.employee.add.html'
})
export class EmployeeAddComponent implements OnInit {
  public employeeList : EmployeeInfo[] = [] ;
  public employee : any = {};

    constructor(
    private _employeeService : EmloyeeService,
    private _route: Router) {
  }

  ngOnInit(){
    this.employeeList = this._employeeService.getEmployeeList();
  }

  addRecord(){
    var lastNo = this.employeeList[this.employeeList.length-1].emp_id;
    if (lastNo == null)
      lastNo = 0;
    this.employee.emp_id = lastNo +1;
    this._employeeService.addEmployeeInfo(this.employee);
    this.navigateUrl();
  }

  navigateUrl(){
    this._route.navigate(['home']);
  }
}


Step 2. Now, open the app.employee.view.html file and add the following code –
<h2>Add Employee</h2>

<form>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Employee Code</label>
        </div>
        <div class="col-sm-8">
            <input type="text" name="emp_code" [(ngModel)] ="employee.emp_code"/>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Employee Name</label>
        </div>
        <div class="col-sm-8">
            <input type="text" name="emp_name" [(ngModel)] ="employee.emp_name"/>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Email Id</label>
        </div>
        <div class="col-sm-8">
            <input type="email" name="emp_email" [(ngModel)] ="employee.emp_email"/>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Mobile No</label>
        </div>
        <div class="col-sm-8">
            <input type="number" name="emp_mobile" [(ngModel)] ="employee.emp_mobile"/>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-sm-4">

        </div>
        <div class="col-sm-8">
            <input type="submit" value="Submit" class="btn-primary" (click)="addRecord()"/>
        </div>
    </div>
</form>

<a href="#">Back to Home</a>


Step 3. Now, add another standalone component called app.employee.add.ts file and add the following code –
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Params, Router } from '@angular/router';

import { EmployeeInfo } from './employee';
import { EmloyeeService } from './app.employee.service';

@Component({
  selector: 'app-employee-view',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './app.employee.View.html'
})
export class EmployeeViewComponent implements OnInit {
  public employee : any = {};
  public employeeId : number = 0;

  constructor(private _employeeService : EmloyeeService,
    private router: Router,
    private route: ActivatedRoute) {
  }

  ngOnInit() {
    this.route.params.subscribe((params: Params)=> this.employeeId = params['id']);
    this.employee = this._employeeService.getEmployee(this.employeeId);
  }
}


Step 4. Now, open the app.employee.add.html and add the following code –

<h2>Employee Details</h2>

<div>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Employee Id</label>
        </div>
        <div class="col-sm-8">
            <span>{{ employee.emp_id }}</span>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Employee Code</label>
        </div>
        <div class="col-sm-8">
            <span>{{ employee.emp_code }}</span>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Employee Name</label>
        </div>
        <div class="col-sm-8">
            <span>{{ employee.emp_name }}</span>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Email Id</label>
        </div>
        <div class="col-sm-8">
            <span>{{ employee.emp_email }}</span>
        </div>
    </div>
    <div class="row mb-3">
        <div class="col-sm-4">
            <label>Mobile No</label>
        </div>
        <div class="col-sm-8">
            <span>{{ employee.emp_mobile }}</span>
        </div>
    </div>
</div>

<a href="/home">Back to Home</a>


Step 5. So, open the app.routes.ts file and add the below component –
import { Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { EmployeeIndexComponent } from './employees/app.employee.index';
import { EmployeeAddComponent } from './employees/app.employee.add';
import { EmployeeViewComponent } from './employees/app.employee.view';

export const APP_ROUTES: Routes = [
    {
        path: '',
        pathMatch: 'full',
        redirectTo: 'home'
    },
    {
        path: 'home',
        component: EmployeeIndexComponent
    },
    {
        path:'employee-index',
        component:EmployeeIndexComponent
    },
    {
        path:'employee-add',
        component:EmployeeAddComponent
    },
    {
        path:'employee-view/:id',
        component:EmployeeViewComponent
    }
];


Now, we can run the application and test the route functionality.



AngularJS Hosting Europe - HostForLIFE.eu :: Routing in Angular

clock July 17, 2023 09:11 by author Peter

This article will discuss Angular routings and the various methods to render different components using routing.


Node Js Angular VS Code
What is Angular?
Popular open-source JavaScript framework for developing web applications is Angular. It was created by Google and is presently maintained by the Google Angular Team. Angular enables developers to create dynamic single-page applications (SPAs) and provides a structured method for constructing complex web applications.
What exactly is Routing?

In web development, routing refers to the process of determining how an application responds to a particular URL or path. It involves mapping URLs to various application components or views and displaying the appropriate content based on the requested URL.

Routing enables users to navigate between various views or pages in a client-side web application, such as a single-page application (SPA) built with Angular, without actually loading a new HTML page from the server. The application instead dynamically modifies the browser's content by loading the required components and data based on the requested route.
Advantages of Routing

Routing in web applications has numerous advantages. Here are several significant benefits of using routing:

  • Improved User Experience Routing enables a fluid and interactive user experience by allowing users to navigate between various views or pages within an application without reloading the entire page.
  • With routing, only the necessary components and data for the requested route are loaded, which results in quicker page transitions.
  • Routing promotes a modular structure for an application by segregating it into distinct views or components associated with specific routes. This facilitates code reuse, separation of concerns, and easier maintenance. Each route can have its own component, making it simpler to administer and independently update distinct sections of the application.
  • Conditional Rendering and Dynamic Content: Based on the current route, routing enables conditional rendering of components. This enables you to display or conceal specific application sections based on the user's navigation path.
  • Route Parameters and Query Parameters: Passing route parameters and query parameters is supported by routing. You can transmit dynamic values in the URL, such as an ID or a username, and retrieve them in the corresponding component using route parameters. Query parameters enable the URL to receive additional data for filtering, categorizing, and other purposes.
  • Route Guards and Security Angular routing includes route guards, which are mechanisms for controlling access to particular routes based on certain conditions. Route guardians can be used for authentication, authorization, and other purposes related to security. They aid in ensuring that users can only access routes or execute actions if they satisfy the required criteria.
  • Routing supports nested or subsidiary routes, enabling you to define a hierarchical navigation structure within an application. This is especially useful when dealing with complex applications with multiple navigation levels or sections that must be encapsulated and managed independently.

Routing has a significant impact on enhancing the user experience, enhancing performance, and facilitating modular and maintainable code structures in web applications.
Routing in Angular

In a client-side web application, such as a single-page application (SPA) developed with Angular, routing enables users to navigate between various views without loading a new HTML page. The application instead dynamically modifies the browser's content by loading the required components and data based on the requested route.

Angular routing typically comprises the following components:

  • Routes: Routes define the correspondence between the URL path and the components to be rendered. Each route is defined with a corresponding URL path and component that will be displayed when that path is accessed.
  • The router interprets the current URL and loads the appropriate components based on the defined routes. It monitors URL modifications and manages navigation within the application.
  • The router outlet is a placeholder within the application's template where the current route's content is rendered.
  • Links and Navigation for Routers: Links and navigation elements, such as anchor tags (a>) or buttons, are used to initiate navigation to various routes within an application. Angular allows these elements to be decorated with directives such as routerLink to specify the intended route.

Routing example in Angular
Step 1
Install NodeJS.

Step 2
Install Angular CLI using the following command.
    npm install -g @angular/cli

Step 3
Verify NodeJS and Angular CLI are installed or not using the following commands:
    node — version



    ng version

Create a new Angular Application.
    ng new RoutingDemo

Step 4
Open the Angular application in one of the editors, like VS Code, and install the bootstrap with the help of the following command:
    npm install bootstrap

next, add the bootstrap script inside the angular.json file inside the scripts and styles section
"styles": [
"src/styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"./node_modules/bootstrap/dist/js/bootstrap.min.js"
]


Step 5
Open your terminal or command prompt and navigate to your Angular project directory. Run the following commands to generate the components:
    ng generate component home
    ng generate component about
    ng generate component contact
    ng generate component feedback
    ng generate component product
    ng generate component product-offer
    ng generate component product-updates
    ng generate component rating


Step 6
Routing Configuration:
Open the app-routing.module.ts file in your project and update the route configuration to include the newly created components.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { ProductComponent } from './components/product/product.component';
import { AboutComponent } from './components/about/about.component';
import { ContactComponent } from './components/contact/contact.component';
import { ProductOfferComponent } from './components/product-offer/product-offer.component';
import { ProductUpdatesComponent } from './components/product-updates/product-updates.component';
import { RatingComponent } from './components/rating/rating.component';
import { FeedbackComponent } from './components/feedback/feedback.component';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' }, //default route
  { path: 'home', component: HomeComponent },
  {
    path: 'product/:id', component: ProductComponent,
    children: [
      {path: '', redirectTo:'updates', pathMatch:'full'},
      { path: 'offers', component: ProductOfferComponent },
      { path: 'updates', component: ProductUpdatesComponent }
    ]
  },
  { path: 'about', component: AboutComponent,
    children: [
      {path: 'rating', outlet:'rate', component:RatingComponent},
      {path: 'feedback', outlet:'feed', component:FeedbackComponent}
    ]
  },
  { path: 'contact', component: ContactComponent },
  { path: '**', component: HomeComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

This configuration maps the respective paths to their corresponding components.

In Angular, the RouterModule and Routes are key components used for configuring and managing routing in an application.

RouterModule

The RouterModule is an Angular module that provides the necessary directives, services, and functionality for implementing routing in an application.

Routes
Routes is an array that defines the routes and their configurations within the application. Each route object within the Routes array specifies the URL path and the corresponding component to be rendered when that path is accessed.

Line No. 13:
To define a default route in Angular, you can use an empty path ‘ ’ as the route path in the Routes array configuration. When the empty path is accessed, Angular will render the component associated with that route.

To redirect to a different route when the default route is accessed, you can use the redirectTo property with a target route path. Additionally, the pathMatch property can be used to define the matching strategy for the route.

Line 15 to 22:
To create a route with an id parameter for displaying product details, you can modify the routing configuration in Angular as follows:
path: 'product/:id', component: ProductComponent

In this example, we’ve added a route with the path ‘product/:id’ to represent the product details page. The :id part indicates a dynamic parameter that can be accessed in the ProductComponent.
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ProductsService } from '../../services/products.service';

@Component({
  selector: 'app-products',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  productDetail? : any;

  constructor(private route : ActivatedRoute,private productService : ProductsService){}

  ngOnInit(): void {
    let productId = this.route.snapshot.params['id'];
    this.getProductDetailById(productId)
  }

  getProductDetailById(id: number){
    this.productService.getProductDetailById(id).subscribe(res => {
      this.productDetail = res
      console.log(res)
    })
  }
}


In this code, we inject the ActivatedRoute service to access the current route’s parameters. In the ngOnInit() lifecycle hook, we retrieve the id parameter using this.route.snapshot.params[‘id’] and assign it to the productId property for later use in the component’s template.

Finally, you can navigate to the product details page by providing an id value in the URL. For example, if you have a product with an id of 123, you can navigate to http://localhost:4200/product/123 to see the product details.

The ProductComponent will be rendered with the corresponding id parameter retrieved from the URL, and you can use the productId property to display the relevant product information in the template.

To create child components, ProductOfferComponent and ProductUpdatesComponent, nested under the ProductComponent, you can modify the routing configuration in Angular as follows:

Update the Routes array in your routing module (e.g., app-routing.module.ts) to include the child routes under the ProductComponent:
{
  path: 'product/:id', component: ProductComponent,
  children: [
    {path: '', redirectTo:'updates', pathMatch:'full'},
    { path: 'offers', component: ProductOfferComponent },
    { path: 'updates', component: ProductUpdatesComponent }
  ]
}


In this updated example, we’ve added child routes to the ProductComponent. The empty path ‘ ’within the children routes corresponds to the ProductComponent as the default component to be rendered when accessing /product. The offers and updates paths map to the ProductOfferComponent and ProductUpdatesComponent, respectively.

Lines 23 to 28:

To create child components RatingComponent and FeedbackComponent nested under the AboutComponent, with named outlets for rating and feedback, you can modify the routing configuration in Angular as follows:

Update the Routes array in your routing module (e.g., app-routing.module.ts) to include the child routes under the AboutComponent with named outlets:
{
  path: 'about', component: AboutComponent,
  children: [
    {path: 'rating', outlet:'rate', component:RatingComponent},
    {path: 'feedback', outlet:'feed', component:FeedbackComponent}
  ]
}


In this updated example, we’ve added child routes to the AboutComponent and specified the named outlet's rate and feed for the RatingComponent and FeedbackComponent, respectively.

Implement the AboutComponent template (about.component.html) to include the named outlets’ placeholders. For example:
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Tenetur magni saepe sint, vel eaque veniam recusandae laboriosam numquam necessitatibus? Laborum mollitia excepturi qui. Modi corporis quasi ab minima eligendi numquam!</p>

<div class="row">
    <div class="col-md-6">
        <router-outlet name="rate"></router-outlet>
    </div>
    <div class="col-md-6">
        <router-outlet name="feed"></router-outlet>
    </div>
</div>


In this template, we’ve added two <router-outlet> placeholders with the name attribute set to ‘rate’ and ‘feed’. These placeholders will be used to render the RatingComponent and FeedbackComponent within the AboutComponent template.

Update the component files for RatingComponent and FeedbackComponent as needed.

Finally, you can navigate to the About and Child components using the named outlets. For example, to access the rating component, navigate to http://localhost:4200/about/(rate:rating//feed:feedback).

I have created an outer link, as I have shown below in the app component. But You can create a URL as per your requirement, and for that, you need appropriate router links with outlets.
<a class="nav-link" [routerLink]="['/about',{
  outlets:{
    'rate': ['rating'],
    'feed': ['feedback']
  }
}]">About</a>


Line No. 30:
In Angular, the double asterisk (**) route, also known as the wildcard route or catch-all route, is used to handle routes that do not match any predefined routes. It acts as a fallback route to handle unknown or invalid URLs within your application.

To define a wildcard route, you can add a route with the path: ‘**’ configuration at the end of your routes array. This route will be matched when no other route matches the requested URL.
{ path: '**', component: HomeComponent }

Step 7
Mention the router outlet in the app component view to conditionally render different components based on navigation.
<nav class="navbar navbar-expand-lg bg-body-tertiary">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">
      <img src="../assets/logo/coder.png" class="navlogo"/> Product Application
    </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a class="nav-link" [routerLink]="['/about',{
          outlets:{
            'rate': ['rating'],
            'feed': ['feedback']
          }
        }]">About</a>
        <a class="nav-link" routerLink="/contact">Contact</a>
      </div>
    </div>
  </div>
</nav>

<router-outlet></router-outlet>


 

So, this is all about routing in Angular.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Deploy an Angular app to Firebase?

clock July 5, 2023 09:44 by author Peter

In this article, we are going to discuss a few things about Firebase and the deployment of Angular applications. Firebase is a mobile and web development platform that provides a wide range of tools and services to help developers build high-quality applications. It was originally developed by Firebase Inc., a startup founded in 2011, and was later acquired by Google in 2014.


Features of Firebase

  • Real-time Database: Firebase provides a cloud-hosted NoSQL database that allows developers to store and sync data in real-time across multiple clients. It uses a JSON-based data model and provides powerful querying capabilities.
  • Authentication: Firebase offers authentication services, enabling developers to easily add user authentication to their applications using email and password, social media logins (such as Google, Facebook, and Twitter), and other identity providers.
  • Cloud Functions: Firebase allows developers to write and deploy serverless functions that run in response to events triggered by Firebase services or HTTP requests. This feature enables developers to extend the functionality of their applications without managing servers.
  • Cloud Storage: Firebase provides secure and scalable cloud storage for developers to store and serve user-generated content like images, videos, and other files. It offers simple APIs for uploading, downloading, and managing files.
  • Hosting: Firebase Hosting allows developers to deploy and host their web applications quickly and securely. It provides a global content delivery network (CDN) to deliver static assets and dynamic content to users with low latency.
  • Analytics: Firebase Analytics provides detailed insights into user behavior and app usage. It helps developers track key metrics, understand user engagement, and make data-driven decisions to optimize their applications.
  • Performance Monitoring: Firebase Performance Monitoring helps developers gain insights into the performance of their applications. It provides real-time monitoring, tracks network requests, and identifies performance bottlenecks.

Register an Application on Firebase

Step 1
Open the following Firebase URL:
https://console.firebase.google.com/u/0/

Step 2
Add a new project.

Step 3
Configure the project name and Google Analytics with some default settings.

Step 3
Configure the project name and Google Analytics with some default settings.

 

 

 

Step 4
Register your application after clicking on the web symbol and copying the project ID that we need for deployment.

 

Create an Angular Demo Application

Step 1
Create a new angular application.
    ng new angular-firebase-deployment

Step 2
Build and run the application.
    ng serve

Step 3
Install the Firebase tool.
    npm install -g firebase-tools

Step 4
Login to the Firebase.
    firebase login

Step 5
Initialize the firebase in your current application.
    firebase init

Firebase CLI will ask you a few questions.

Which Firebase CLI features do you want to set up for this folder?
Press space to select the required feature, then enter to confirm your choices.
Select a default Firebase project for this directory: angular-demo-5658b
Here I selected angular-demo-5658b, which I created earlier.
What do you want to use as your public directory? (public) dist/angular-firebase-deployment
configure as a single-page app (rewrite all URLs to /index.html)? (y/N) Yes
The File dist/angular-firebase-deployment/index.html already exists. Overwrite? Yes
If you select Configure files for Firebase Hosting and (optionally) set up the GitHub Action Deploy option from the list at the initial level, then you need to have a repository on GitHub, and then only you can set up and configure workflow after giving access to that particular repository.


 

Create a production build using the following command:
    ng build –aot

It will create one dist folder in your project solution. dist/angular-firebase-deployment

Step 7
Execute the following command to deploy your Angular application on Firebase:
    Firebase deploy

Step 8
Finally, open the browser and open the hosting URL.




AngularJS Hosting Europe - HostForLIFE.eu :: Simplifying Usage of trackBy in Angular Directives for Effective Item Tracking

clock June 20, 2023 10:23 by author Peter

When working with lists and data rendering in Angular, it is essential to efficiently maintain track of the rendered items. A common challenge is maintaining the integrity of the rendered objects while dynamically updating the list. By utilizing the trackBy directive, Angular provides us with syntax sugar that simplifies this endeavor. This article will examine how to leverage the power of trackBy to efficiently keep track of rendered items.

Knowledge of the trackBy Directive
Essential to Angular, the trackBy directive optimizes rendering by associating a unique identifier with each list item. Using the trackBy directive, Angular can efficiently detect changes and update only the required DOM elements, resulting in enhanced performance.

Syntax and Usage

To use trackBy, please follow these steps:

Step 1. Define a Unique Identifier: Ensure that each list item in your component has a unique identifier. This is possible by incorporating an id property into your data objects.

export interface Item {
  id: number;
  // Other properties
}

// Example data
items: Item[] = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  // Additional items
];

Step 2. Specify the trackBy Function: Next, create a method in your component that acts as the trackBy function. This function will be responsible for returning the unique identifier for each item.
trackByFn(index: number, item: Item): number {
  return item.id;
}

Step 3.  Apply trackBy in Template: In your HTML template, apply the trackBy directive by binding it to the ngFor loop.
<ng-container *ngFor="let item of items; trackBy: trackByFn">
  <!-- Render item here -->
</ng-container>

The benefits of using the trackBy Directive offer
Improved Performance: By associating a unique identifier with each item, Angular can efficiently track changes and update only the affected elements, resulting in optimized rendering performance.

Reduced DOM Manipulation: With trackBy, Angular avoids unnecessary DOM manipulations by reusing existing elements when the data changes, leading to a smoother user experience.

Simplified Syntax: The syntax sugar provided by the trackBy directive simplifies the usage and implementation of item tracking in Angular, making the code more readable and maintainable.

By utilizing the syntax sugar of Angular directives, specifically the trackBy directive, we can easily maintain good track of rendered items in our Angular applications. By following the steps outlined in this article, you can optimize performance, reduce unnecessary DOM manipulations, and simplify the codebase. Leveraging the power of trackBy, you can build responsive and efficient Angular applications with ease.




About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in