Angular Tutorials | Learn Angular Step By Stepfrom Scratch

Angular Tutorials | Learn Angular step by stepfrom scratch

In this Angular tutorials , we won't be writing any code rather we will have a higher level view of how to think of angular architecture in terms of angular module or angular ngmodule

What is Angular

A Very High-Level View of angular

angular is a Framework Which allow us to create a simple angular app a client-side application in HTML and typescript (a language which compiles down to javascript)

NGModules in detail

Every angular Application contains at least one root angular module in it which is specific to the angular module(not javascript modules) and is decorated with NgModuledecorator and typically named as app module
Now it's not compulsory that it will have only one angular module and we will dig into it more but for now
An angular application is a set of angular modules and each angular module can be considered as a group of related things, basically modularizing an application means breaking and organizing the angular application into sensefull pieces so that we can reuse our code, manage our code and it increases the performance also with the help of lazily loaded angular modules again we will get back to it shortly,moreover angular modules consolidate angular components, angular directives, and angular pipes into cohesive blocks of functionality and this modules can be used by other angular modules in your application
ngmodules are typescript classes which are just decorated with @NgModule Decorator

it has 4 things in it they are

  1. Declaration: this property tells angular that which components, pipes, and directives are part of these modules. It's kind off we are binding our component directive to a ngmodule
  2. Providers: In this propert, we will register our services in the ngmodules which are required by our components in the modules or which can be consumed by other modules when they import this module
  3. Import: if we want to use some other module in our ngmodule we have to import that module in this property
  4. Export: in this property, we register those components, directives, and pipes which we want to make public so that other module's component templates can use them.

@NgModule({
  imports: [CommonModule, SharedModule,
    FormsModule,  FilterPipeModule,
    MDBBootstrapModulesPro.forRoot(),
    RouterModule.forChild(routes)],
  exports: [RouterModule],
  declarations: [BlogComponent, BlogDetailComponent,BlogCReatorComponent, EvenblogComponent, OddblogComponent]
})
export class BlogModule {}

Thinking of application in ngmodules

Suppose you have an e-commerce application where a customer can register login change password manage his account see his orders and the admin can add ducts change the price of the products add images of the products. A customer can purchase a product and pay for it

Angular Tutorials | Learn Angular step by stepfrom scratch

just try to imagine it and come up with how many ngmodules you can have in it I think we can have multiple ngmodules in it
we can see r specific functionality in it so we can encapsulate register login change password manage account into a module and we can name it as UserModule or more specifically CustomerModule
And Similarly we can have Admin module which has specific permissions and we can group the product and shipment related stuff in it and name it something like InventoryModule

Angular Tutorials | Learn Angular step by stepfrom scratch

SharedModule

now the interesting thing suppose for orders we have one service which gives us a list of orders based on user now if we see closely this service will be used by both the modules CustomerModule (as the customer should be able to see his orders ) and InventoryModule (as admin can also see the orders and dispatch them 
 
so this order service is a very good condition to make it shared so what we will do is we will create a shared module which will be used by both other modules

Angular Tutorials | Learn Angular step by stepfrom scratch

NOTE: I know it can be improved upto a very good extent but this is only to grab the concept of using ngmodules

Lazy Loaded Module

Now I hope you have a pretty good understanding of angular modules now let's dig a bit more into it 

So now the admin functionality is totally different from Customer functionality but when we make a build or run our application it does not matter which module I am on whether I am admin or customer the code behind will have the logic of both the modules

Angular Tutorials | Learn Angular step by stepfrom scratch

So as you can see we obviously have a performance issue the code which I am not us that is also being loaded in the browser to overcome this situation we can make our modules loaded on demand typically based on routing

Angular Tutorials | Learn Angular step by stepfrom scratch

so that it, for now, hope it may have helped you if it does
Thanks a lot for more this kind of articles visit Best Angular Tutorials

What to expect

In this Angular Tutorials, ill tell you how you can quickly set up your development environment how to install angular cli and generate a new angular project with angular cli commands

First thing First

the base will be installing node js as all the dependencies of angular core angular cli and their sub-dependencies will be installed as the node packages and will be connected with npm

Installing Node js

Head over to nodejs.org official website of node js and based on your platform we need to install the node installer with Stable node js version. when you visit nodejs.org, you will see a page like this

Angular Tutorials | Learn Angular step by stepfrom scratch

So you will have two options to install node js. Make sure you install the LTS node js version the current node js version will have test features, but the latest breaking changes and you don't want to mess with it 
so based on your platform download the installer and install node js on your pc
now to verify whether node js is installed or not we will check the version of the node which will give us the node js version on our pc

node -v
Angular Tutorials | Learn Angular step by stepfrom scratch

Installing Angular cli

first, let answer what is angular cli
Angular CLI is a command line interface, thus 'CLI', which includes the functionality that WebPack provides. It uses Webpack to include all the packaging, importing, BrowserLink, etc., but you do not need to know how Webpack works or how it needs to be configured to run in different environments or on different types of machines. All the Webpack configuration is done completely by CLI and leaves it out of the hands of a developer unless they choose to adjust the settings themselves. In addition, CLI assists developers by generating code which follows the best practices as defined by https://Angular.io, Angular's home site.

Angular cli version

The angular cli latest version as of now is 7.3.8 to install this version we will run the command below it will install angular cli latest version globally because we have used -g flag which stands for - globally so that we can access angular cli from anywhere in our system
The other version (not recommended) which is in beta is 8.0.0-RC if you know what you are doing then you can install this current unstable version by this npm command

npm i -g @angular/cli@latest

so to verify if the angular cli is installed correctly on your system or not we will check the angular cli version by running

ng --version
Angular Tutorials | Learn Angular step by stepfrom scratch

So that's it you have your angular development environment you can go ahead and create your first angular project by running

ng new yourawesomeprojectname

this command will generate a brand new angular scaffolded project template for you where you can start your angular development and hit ng serve remember you have to be inside an angular-cli project in order to use the serve command.  Thanks a lot, Visit Smartcodehub for Best Angular Tutorials

What To expect

In this angular tutorial, we will see how we can integrate bootstrap with angular to build a beautiful experience

Bootstrap

World most famous front-end component library to Build responsive, mobile-first projects on the web  It is a free and open-source CSS framework. It contains CSS- and (optionally) JavaScript-based design templates for typography, forms, buttons, navigation, and other interface components

Setting Up An Angular Project With Angular CLI

First, let's start by creating a new Angular project. The easiest way to do so is to use the Angular Command Line Interface (CLI) to generate a new project. First, you need to make sure that Angular CLI is installed on your system. As Angular CLI comes as an NPM package the installation can be done by using the following command
For more details visit Angular Tutorials- Development Environment Setup an article where I showed how to quickly set up your development environment ok so once you have your project ready go ahead and hit ng serve -o and your application will start

$ npm install -g @angular/cli

Install Bootstrap

Now that the Angular project is ready and running we can continue and add Bootstrap to the project. There are different ways of adding bootstrap to our project.

Using Bootstrap CDN

head over to get bootstrap the official website of bootstrap and hit on get started button 
Copy-paste the stylesheet into your before all other stylesheets

<head>
  <meta charset="utf-8">
  <title>Projectone</title>
  <base href="/">
<!-- Bootstrap css -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
  integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 
  crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

the next step is to paste all the js scripts in your body tag at the end

<body>
  <app-root></app-root>
<!-- Bootstrap Scripts -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
    
</body>

your full html will look like this

Angular Tutorials | Learn Angular step by stepfrom scratch

Using Bootstrap with npm

the other way to use bootstrap is to install bootstrap as an npm package and then use  Bootstrap depends on Jquery and popperjs so we will need to include that also as a peer dependency

npm i jquery popperjs bootstrap --save

the above command will install jquery popperjs and bootstrap as pm package now we need to configure css and js in our angular.json file (the recommended way)
so head over to your angular.json file and there you will find a styles array and scripts array  just paste this lines (nothing more than imports of css and js from node_modules)

"styles": [
              "src/styles.scss",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
"scripts": [
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/popper.js/dist/umd/popper.min.js",
              "./node_modules/bootstrap/dist/js/bootstrap.min.js"
            ],

once you do that restart your application as whenever you make any changes to the angular.json file you need to restart the application  Visit Smartcodehub.com

What To expect

In this Angular tutorial, we will see how and why we use angular ngclass directive. how to use it efficiently How we can apply ngclass conditionally in angular

Initial Setup

let's say we have an angular project in which we show todo list, and we have a type todo which will have four properties

type ToDo = {
  userId: number,
  id: number,
  title: string,
  completed: boolean
}

and in angular component we fetch todo list with httpclient
for now i am using fake api to fetch some test json data

import { Component ,OnInit} from '@angular/core';
import {Observable} from 'rxjs'
import {HttpClient} from '@angular/common/http'
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
todos$:Observable<ToDo[]>;
ngOnInit(){
    this.todos$ = this.http.get<ToDo[]>('https://jsonplaceholder.typicode.com/todos')
}
constructor(private http:HttpClient){
}
}

and in our appcomponent html we have

<div class="container">
  <div class="row" *ngFor="let todo of todos$|async">
   
<div class="card   mb-3" style="max-width: 18rem;">
  <div class="card-header ">{{todo.id}} Todo</div>
  <div class="card-body">
   
    <p class="card-text">{{todo.title}}</p>
  </div>
</div>
  </div>
</div>

I am using Bootstrap to make things look prettier
and with this angular bootstrap project, we will have the result as follows

Angular Tutorials | Learn Angular step by stepfrom scratch

now each todo has a complete property attached to it which shows whether the todo is completed or not its value is boolean
and I want to apply angular class conditional to the header based on that boolean property which is completed
let's create the first two classes with this styling

.card-incomplete{
  background-color: red;
  color:white;
}
.card-complete{
  background-color: green;
  color:white;
}

ngClass

ngClass is an angular directive which shifts with an angular bundle 
we can use angular ngclass in many ways

1. ) we can pass a static string or array of strings to ngClass like

[ngClass]="'card-incomplete'"
//for passing and array
[ngClass]="['card-incomplete','card-incomplete-text']"

2. ) we can pass a variable to ngclass directive and sets its value from the appcomponent like

//in component
completeClass="card-incomplete"
//in html template
[ngClass]="completeClass"
//for passing an array for multiple classes
//in ts
completeClass="card-incomplete"
completeTextClass="card-incomplete-text"
in html
[ngClass]="[completeClass,completeTextClass]"

3.) we can pass a configuration object in ngclass in which the properties are the class names and values are true or false if the value is true the class will be added if it is false class will not be added lets see it in code

[ngClass]="{'card-incomplete':true,'card-incomplete-text':false}"

in the above code snippet, 'card-incomplete' will be added as its value is true and card-incomplete-text won't be added as its value is false
in this way, we can add angular class conditional

4.) we can even pass a function the condition is the function should return the classes in string format lets say we have a function which returns a class

getSuccessClass(){
   return 'card-incomplete';
}
//in html


[ngClass]="getSuccessClass()"

so this way we can add angular class conditionally, and we will see it in action soon
I think now you have a clear understanding of how to use the ngclass directive in angular, so let's go back to our original project of todo above, and it's a small practice 
what you have to do is for all todos who's completed property is true you have to render a class with green, and for completed false, you have to make red color

well you can find the code below

Thanks a lot for more this kind of articles visit Best Angular Tutorials

In this Angular Tutorial, we will learn about the ngstyle directive, why we need it, and the different ways of using angular style binding.
Inline styles are the most used way to apply small styles to elements.

//For coloring a div
<div style="background:#333"></div>

Now, to apply styles in angular, we can use input functions and pass style to it:

//For coloring a div
<div [style.background]="bgColor"></div>
// in ts file
public bgColor:string = '#333';

Suppose we want to apply one more style to it for our text color:

//For coloring a div
<div [style.background]="bgColor"
[style.color]="txtColor"
></div>
// in ts file
public bgColor:string = '#333';
public txtColor:string = '#fff';

Now the problem with this approach is you have to rewrite [style.[styleName]] multiples times for all the styles which you want to apply to. So to solve that problem, we have ngStyle Directive.
ngStyle Directive expects the value as a configuration object, with each property as a key/value pair. Let’s take a look at the code:

//For coloring a div
<div [ngStyle]="{'background-color':bgColor,'color':txtColor}"
></div>
// in ts file
public bgColor:string = '#333';
public txtColor:string = '#fff';

As expected, our code looks much cleaner and readable. But it gets better — you can even use angular style binding conditionally.
Suppose you have a boolean property and based on that property, you want to change the background color of the div:

//For coloring a div
<div [ngStyle]="{'background-color': condition?bgColordark:bgColorlight,'color':txtColor}"
></div>
// in ts file
public bgColordark:string = '#333';
public bgColorlight:string = 'yellow';
public condition:boolean= true;
public txtColor:string = '#fff';

Just like the case of angularngClass, if our ngStyle expression starts to get too large, we can always call a component method to get the configuration object:

<div [ngStyle]="GetStyles()"
></div>
//in ts 
public bgColordark:string = '#333';
public bgColorlight:string = 'yellow';
public condition:boolean= true;
public txtColor:string = '#fff';
public GetStyles:any{
   return {'background-color': this.condition?        this.bgColordark:this.bgColorlight,
'color':this.txtColor};
}

Thanks a lot. For more of this kind of angular tutorials and articles visit Smartcodehub.

In this Angular tutorial , we will see how the dependency injection in Angular works internally. this is also a frequently asked angular interview questions
Suppose we have a component named appcomponent which has a basic and simple structure as follows:

import { Component, OnInit } from "@angular/core";
@Component({
  selector: "my-root",
  templateUrl: "app.component.html",
  styleUrls: ["app.component.css"]
})
export class AppComponent implements OnInit {
  ngOnInit(): void {
    
  }
}

And we have a service class named GreetingService with a function in it sayHello which has a name as a parameter and returns the name with “Hello” in front of it.

export class GreetingService{
  sayHello(name){
    return `Hello ${name}` ;
  }
}

There are two ways to use the service class in the component: first, we can manually create an instance of the service in the component (this is the wrong way and is never recommended).
And the other way is to let Angular create the instance of our service and pass that instance to our component internally. This is the common and recommended way to do it.

Injecting our service in the Angular dependency injection system

Now if you run this project, you will get the error “No provider for GreetingService!”

Import {Component} from '@angular/core';
Import {GreetingService} from '. /greetingService';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
constructor(private greetingService : GreetingService){
   console.log(this.greetingService.sayHello());
  }

}
Angular Tutorials | Learn Angular step by stepfrom scratch

So, basically Angular is complaining that it did not find any provider for creating an instance of the greeting service or it does not know how to create an instance. In order to let the framework know how the instance should be created, we have to pass a provider object to the providers property in the component decorator shown below:
In this provider object, we have many properties so let us understand them one by one.

import { Component } from '@angular/core';
import {GreetingService} from './greetingService';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers:[{
    
  }]
})
export class AppComponent  {
constructor(private greetingService : GreetingService){
   console.log(this.greetingService.sayHello());
  }
  
}

Custom Factory

use factory: this will tell the framework which factory will be used while creating the object of the service. In our case, we don’t have any factory so let’s create one.
The factory will be a function which will be responsible for creating and returning the object of the service.

export function greetingFactory(){ 
  return  new GreetingService()
};
Or more short way
export const greetingFactory= () =>  new GreetingService ();

Custom Injection Token

The next thing is to create a property whose value will be an Injection Token instance. Using this property, the framework will uniquely identify our service and will inject the right instance of the service.

var greetingTokken = new InjectionToken<GreetingService>("GREET_TOKEN");

So in the above snippet, we are creating an instance of the InjectionToken class and it is generic. In our case, the GreetingService instance will be injected when someone asks for the injection with name greetingToken.
So far now our code will look like this:

import { Component ,InjectionToken} from '@angular/core';
import {GreetingService} from './greetingService';
export const greetingTokken = new InjectionToken<GreetingService>("GREET_TOKEN");
export const greetingFactory=()=>  new GreetingService();
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers:[{
    provide  : greetingTokken,
    useFactory : greetingFactory,
   
  }]
})
export class AppComponent  {
constructor(private greetingService : GreetingService){
   console.log(this.greetingService.sayHello());
  }
  name = 'Angular';
}

But then also we will have the same error:

Angular Tutorials | Learn Angular step by stepfrom scratch

This is because in the constructor, where we are asking for the instance of our service, we have to tell it the unique string of our injection token that is greetingToken.
So let’s update our code:

export class AppComponent  {
constructor(@Inject(greetingTokken) private greetingService : GreetingService){
   console.log(this.greetingService.sayHello('Neeraj'));
  }
  name = 'Angular';
}

and now we will have the result that allows us to successfully pass a service from Angular dependency injection

Angular Tutorials | Learn Angular step by stepfrom scratch

Now let us assume you have some nested dependencies like this:

import{DomSanitizer} from '@angular/platform-browser';
export class GreetingService{
  constructor (private domSanitizer:DomSanitizer){
    
  }
  sayHello(name){
    return `Hello ${name}`
  }
}

So, in this case, we have to pass one more property to the provider’s object (that is deps) which is the array of all the dependencies:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers:[{
    provide  : greetingTokken,
    useFactory : greetingFactory,
    deps:[DomSanitizer]
   
  }]
})
export class AppComponent  {
constructor(@Inject(greetingTokken) private greetingService : GreetingService  ){
   console.log(this.greetingService.sayHello('Neeraj'));
  }
  name = 'Angular';
}

Up until now, whatever we have done has only been for learning purposes. It is not recommended to create manual providers until there is a need.
So this is all the hard work done by Angular behind the scenes for us. We don’t have to do all this for registering our service. We can actually reduce the code, and instead of passing the factory and token manually, we can ask the framework to do this for us in that case.
The provide property, which is the injection token, will be the name of the service and Angular will internally create an injection token and factory for us.
We have to pass one more property (use-class) which tells the framework which class we need to use:

import { Component ,InjectionToken,Inject} from '@angular/core';
import {GreetingService} from './greetingService';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers:[{
    provide  : GreetingService,
    useClass :GreetingService
   
  }]
})
export class AppComponent  {
constructor( private greetingService : GreetingService  ){
   console.log(this.greetingService.sayHello('Neeraj'));
  }
  name = 'Angular';
}

So now our code looks much cleaner and we can further reduce it by just passing the name of the service. Then Angular under the hood will create the provide object, the factory, and the injection token for us and make the instance available to us when needed.

import { Component } from '@angular/core';
import {GreetingService} from './greetingService';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers:[GreetingService]
})
export class AppComponent  {
constructor( private greetingService : GreetingService  ){
   console.log(this.greetingService.sayHello('Neeraj'));
  }
  name = 'Angular';
}

So in the end, our code looks very familiar. Now in the future, whenever you create a service, you know exactly what steps are involved to get that instance available.
If you like this article follow me to get more of this kind of stuff.

In this Angular tutorial, we will see how to handle injectables in Angular in more detail. and this is also a most asked angular interview questions
We have seen before how our services are being registered in the Angular dependency system — you can read about it here.
You will notice that in our service did not use any decorator for services, such as an Injectable.

Now let us suppose we have two services one of them is SQLService, and the other is an Oracle service. We have registered both the services in the app component level and notice we are using SQL service in app component.

import { Component } from '@angular/core';
export class SQLService {
  constructor() {
    console.log("SQLService")
  }
}
export class OracleService {
  constructor() {
    console.log("OracleService")
  }
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [OracleService, SQLService]
})
export class AppComponent {
  constructor(private service: SQLService) {
    console.log(this.service)
  }
  name = 'Angular';
}
Angular Tutorials | Learn Angular step by stepfrom scratch

Angular will only provide the instance of the service if it was requested somewhere else it wont create the instances of dependencies for example if we remove the constructor of app component it will not instantiate the sqlservice instance
Now let’s open the dev tools and go to the source tab and see the main.js file over there and search for oracle keyword as shown in the image below.

Angular Tutorials | Learn Angular step by stepfrom scratch

So we will see although we are not using Oracle service anywhere in our code then also it’s been included in the main bundle on angular which increases the size of the primary packet and is directly proportional to the speed of our app.
So the conclusion is that only those files should be included in the main bundle which is required or demanded as the dependency by other pieces.
In solving this problem, Injectable comes into the picture. So iI highly recommends reading my last article . if you are not already familiar with the configuration object required to register a service in Angular.

Angular Tutorials | Learn Angular step by stepfrom scratch

So we have looked to provide a property which is an instance of the injection token which helps Angular to identify our dependency uniquely. The other one is a useFactory, function responsible for creating the instance of our dependency and which deps is an array which contains all sub-dependencies if it exists.
We will now remove both the services from our providers array and decorate the services with an injectable decorator who also accepts a configuration object similar to providers configuration object so let’s have a look at it:

Angular Tutorials | Learn Angular step by stepfrom scratch

In this object, there is a mandatory property that is whichprovidedIn is by default “root.”
the other property is useFactory which will a function responsible for creating the object of our dependency so now our code will look something like this:

app.Component.ts
import { Component, Injectable } from '@angular/core';
import { SQLService } from './service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(private service: SQLService) { }
  name = 'Angular';
}
sqlservice.ts
import { Injectable } from '@angular/core';
@Injectable({
    providedIn:'root',
    useFactory : ()=>new SQLService()
  })
export class SQLService {
  constructor() {
    console.log("SQLService")
  }
}
oraclseservice.ts
import { Injectable } from '@angular/core';
@Injectable({
    providedIn:'root',
    useFactory : ()=>new OracleService()
  })
export class OracleService {
  constructor() {
    console.log("OracleService")
  }
}

Now you can see that we have injected the SQL service into our app component and we are not using the Oracle service so let us go to the main.js in the source tab of our browser Dev Tools and search for SQL and Oracle. We will see that we have 0 occurrences of Oracle and some occurrences of SQL.

Angular Tutorials | Learn Angular step by stepfrom scratch

This kind of on-demand provider is known as a Tree Shakable provider, used by Angular’s dependency injection system in a way that can improve the performance of an Angular application. Don’t hesitate to clap or follow if you learn something new. Thanks!
Thanks a lot for more this kind of articles visit Best Angular Tutorials

What to expect

In this Angular tutorial, we will try to answer the most asked angular interview questions how angular environment file works. We will create our custom config files and inject them into our application based on the mode (development or production ). It would be somewhat the same as our environment files.
So let’s start with the basic template.

Angular Tutorials | Learn Angular step by stepfrom scratch

Now let’s start by adding a config file in our project which exports an object and let’s name that as ConfigurationObject. to keep things simple I have attached only two properties to it. One property is the URL, and the other is the mode.

export const ConfigurationObject :any={
 url:'http://localhost:9001',
 isProduction:false
}

Let’s create one type also which has the same definition as our Configuration object. So now our code will look something like:

// this is our type 
export interface Configuration{
 url:string,
 isProduction:boolean
}
// and this is our config file
import {Configuration} from '../Models/Configuration'
export const ConfigurationObject :Configuration ={
 url:'http://localhost:9001',
 isProduction:false
}

In my last article, I have explained in detail how angular dependency injection works and how you can inject your services manually. If you want to read about it, you can read it here.
I hope you have read the above article and now you know how we inject anything in angular dependency injection. So let’s take that concept and implement it in our scenario.
We need two things to register our configuration object in angular dependency injection they are
1.) InjectionToken
2.) Factory
So let’s create them. We will start by creating injection token first.

import { Component,InjectionToken } from '@angular/core';
export const configInjectionTokken = new InjectionToken<any>('CONFIG_TOKEN');

The other will be a factory which will be a function returning the object.

export const configurationFactory=()=>{
 return ConfigurationObject;
}

Let’s use this factory and token in the providers array at our component level so n our appcomponent e will make these changes.

@Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: [ './app.component.css' ],
 providers:[{
 provide:configInjectionTokken,
 useFactory:configurationFactory
 }]
})

Now let’s ask for this object from the angular framework in-app component with injection token,

@Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: [ './app.component.css' ],
 providers:[{
 provide:configInjectionTokken,
 useFactory:configurationFactory
 }]
})
export class AppComponent {
 name = 'Angular';
constructor(@Inject(configInjectionTokken) private data:Configuration){
 console.log(this.data)
 }
}
Angular Tutorials | Learn Angular step by stepfrom scratch

let’s add one more file and have in this kind of structure
We have two different data files based on the environment. One is for development, and one is for production. The surprising thing is that if we use separate files based on the mode, we don’t have to make any changes in our code. We have to make a small change in our angular.json file. It has a property named configurations, and under that production and under that file replacement it’s an array of objects which has two properties. So as the name suggests our code will look like this

"configurations": {
 "production": {
 "fileReplacements": [
 {
 "replace": "src/app/configs/devConfig.ts",
 "with": "src/app/configs/prodConfig.ts"
 }],
 },
 // other properties will come here
}
Angular Tutorials | Learn Angular step by stepfrom scratch

So now you will have different values based on your environment Thanks for taking the time to read this let me know if it is helpful
Best Angular tutorial

Show Us Your Support And Share Us On