Showing posts with label Angular. Show all posts
Showing posts with label Angular. Show all posts

How to Create a new project in Angular 15 | Create Angular 15 First application

 We know angular 15 is released in November 2022, so now in this article, we will see how to create an Angular 15 project.

See the Angular15 new features Article Link or Angular15 features Video link.

If you have already worked with angular previously we know, angular CLI helps us to build an angular application. Creating a new project in angular is now as simple as installing the Angular CLI and running the ng new command.

What is Angular CLI

The Angular CLI helps us to create an Angular application and it uses Typescript, it creates an angular application with all the configuration files and the packages in one single command.

It helps us to add features (components, pipe, services, directives, etc.) to existing or new Angular applications.

How to create a new Angular15 project

To create a new angular15 project, 1st we need to set up the system environment

Installing Visual Studio Code

We need an editor to create the application so for that we need to install VS code, it is easy to install and helps us to create an angular application easily. You can download Visual Studio Code from the following link.

Node.Js

Node.js is the open source, cross-platform javascript run time environment.

Go to https://nodejs.org/en/

And install the LTS version

Install the Package Manager

To install Angular and its dependencies, we now need to install Node Package Manager ( NPM).

NPM is the node.js package manager for JavaScript, which is automatically installed when we install node.js.

To see the version of NPM, run the below command on the Node.js command prompt like below

Node -v



Typescript

Go to the Node.js command prompt and install typescript using the below command

Npm install –g Typescript

Angular CLI (command line interface)

It is a tool that allows us to create a project using the command line argument.

So below is the command to create the latest angular project

npm install -g @angular/cli@latest

Once the above command runs successfully, now check the latest version of angular and run the below command

Ngversion

Since I was working already I angular 14 previously, so for me only I need to run the Angular CLI command.

Below is the image when my angular version is v14,



Now I ran below CLI command and then check the angular version like the below image

npm install -g @angular/cli@latest



So this is the way we can upgrade the angular version to the latest version.

You can also install the older version of Angular as shown below,

  • MDAngular8
  • cdAngular8
  • npmi @angular/cli@8.3.8

Now to create an Angular15 application run the below command

Ng new Angular15App

Once you run the above command it will ask for installing routing like below, give Y and press enter





After that, it will ask to add CSS like the below,





Once you press enter, it will take a few minutes to create the Angular 15 Application.





So from above, we can see, the angular15 project creation is in progress.





From the above image, we can see, the angular 15 projects was created successfully.

After Creating this project, now let's open the VS code, go File tab then select the folder, and go to the directory where we created the angular15 project, from there, select the angular15 project folder. Once you will load the project, you will see all files in VS code.

Now run the ng serve –o command, 

 If you face an error like below then delete ng.ps1 file

PS C:\Users\DELL\Angular15App> ng serve -o

ng : File C:\Users\DELL\AppData\Roaming\npm\ng.ps1 cannot be loaded. The file C:\Users\DELL\AppData\Roaming\npm\ng.ps1 is not digitally signed.

You cannot run this script on the current system. For more information about running scripts and setting execution policies, see

about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.



Then follow the below points then run ng serve –o again,

  • Delete ng.ps1 from the directory C:\Users\% usernam%\AppData\Roaming\npm\
  • Try to clear the npm cache directory C:\Users\%usernam%\AppData\ Roaming\npm-cache\

Note:- Sometimes without clearing the cache also, the above error is resolved.


Now run the ng serve –o command, Again, you will see output like below



Now to verify that this application is created in Angular15, just go to the package.json file and see all the libraries are in v15 like below.





To build the application below is the command 

ng build

To run the application below is the command

ng serve

after serving the application, go to the browser and enter the below URL, this is the default URL where the angular application run.

http://localhost:4200/

If you are looking Practically, then see the below video,




 

 

-------------------------------------------------------------------

Angular 15 New Features | Angular v15 is now available!

After the releasing Angular 14 this year, now Angular 15 is released this month (November 2022) with a couple of features including performance improvement. Previously we saw a new feature added to Angular 14. The released Angular 15 version is a stable version.
In this article, we are going to discuss the new feature added to Angular 15.



Angular 15 new features

  1. Stable Standalone Components API
  2. Standalone APIs to create a multi-route application
  3. Directive composition API
  4.  Image Directive (NgOptimizedImage) is now Stable
  5. Functional router guards
  6. The router unwraps default imports
  7. Better stack traces
  8. Stable MDC-based Components
  9. CDK Listbox
  10. Extended esbuild support



In this article, we are going to discuss the above Topics.

 
1.       Stable Standalone Components API

We see in Angular 14, the standalone APIs introduced to create angular applications without using the NgModules.
In Angular v15, standalone APIs are now stable after a couple of observation-like performances by the angular team.
In Angular v15, the Angular developer team achieved stability so now standalone components can work in sync with HttpClient, routers, Angular Elements, and more.
 
Standalone API allows us to bootstrap an application in a single component.
Here’s the code to do this:



import {bootstrapApplication} from '@angular/platform-browser';
import { StudentNameComponent } from './StudentName/StudentName.component';
@Component({
  standalone: true,
  selector: 'student-Names',
  imports: [StudentNameComponent],
  template: `
    … <student-grid [stdNames]="stdNamesList"></student-grid>
  `,
})
export class Angular15AppComponent {
  // component logic
}
bootstrapApplication(Angular15AppComponent);


Using the imports function, we can also reference standalone directives and pipes.
 
We can now mark components, pipes, and directives as “standalone: true” – now, no need to declare them into NgModule, else the Angular compiler will throw an error.
We can now import NgModule directly inside the standalone component by using import: [module_name].


2. Standalone APIs to create a multi-route application
Now we can build the multi-route application using the new router standalone APIs.

export const appRoutes: Routes = [{
    path: 'lazy',
    loadChildren: () => import('./lazy/lazy.routes')
      .then(routes => routes.lazyRoutes)
   }];

Where lazyRoutes are declared in

import {Routes} from '@angular/router';
import {LazyComponent} from './lazy.component';
export const lazyRoutes: Routes = [{path: '', component: LazyComponent}];

and now, register the appRoutes in the bootstrapApplication call 

bootstrapApplication(AppComponent, {
    providers: [
      provideRouter(appRoutes)
    ]
  });


here  provideRouter API is the tree-shakable.
At the build time, Bundlers can remove unused features from the router that reduce around 11% of code bundle size.

3. Directive composition API


This feature is implemented because of a feature request created on GitHub for adding the functionality to add directives to the host element.
it helps us in code reusability and it also allows developers to increase host elements with the directives and build the angular application with the help of code reusability, and it is possible with the help of the angular compiler.
The directive composition APIs only work with the standalone directives

@Component({
    selector: 'mat-menu',
    hostDirectives: [HasColor, {
      directive: CdkMenu,
      inputs: ['cdkMenuDisabled: disabled'],
      outputs: ['cdkMenuClosed: closed']
    }]
  })
  class MatMenu {}


in the above code, we enhance MatMenu with the 2 directives called HasColor and CdkMenu.
MatMenu helps us to reuse all the inputs, outputs, and related logic with HasColor and only logic and the selected input from the CdkMenu.


4. Image Directive (
NgOptimizedImage) is now Stable


The NgOptimizedImage was introduced in V14.2, which helps us to easily adapt for loading image performance.
Now in Angular v15, it is stable.  Land’s End worked with this feature and introduced a 75% improvement in LCP (Largest Contentful Paint) in a lighthouse lab test for image loading.




previous version NgOptimizedImage having many features and functionalities, 
Now Angular v15 updates added a couple of new features in the image directive.

  1. Automatic srcset Generation: this directory automatically generates the srcset, which helps us to upload an appropriately sized image whenever requested. This reduces the download time of an image.

  1. Fill Mode [experimental]: this mode removes the need for declaring image dimensions and fills the image to its parent container. This mode is useful when we don't know the image dimensions we need to migrate the CSS background image to make use of this directive.

with the use of NgOptimizedImage directive, We can directly use NgOptimizedImage directive in angular component or NgModule

import { NgOptimizedImage } from '@angular/common';

// Include it into the necessary NgModule
@NgModule({
 imports: [NgOptimizedImage],
})
class AppModule {}

// ... or a standalone Component
@Component({
 standalone: true
 imports: [NgOptimizedImage],
})
class MyStandaloneComponent {}

when we are working with NgOptimizedImage  directive within a component, then we need to replace the image src attribute with the ngSrc.

5. Functional router guards
With the help of tree-shakable standalone router APIs, we work on reducing the boilerplate in the guards.

@Injectable({ providedIn: 'root' })
export class MyGuardWithDependency implements CanActivate {
  constructor(private loginService: LoginService) {}

  canActivate() {
    return this.loginService.isLoggedIn();
  }
}

const route = {
  path: 'somePath',
  canActivate: [MyGuardWithDependency]
};

here LoginService implements most of the logic and in the guard we only invoke isLoggedIn(). Even though the guard is pretty simple, we have lots of boilerplate code.
Now with the new functional router guards, we can refactor the code like below.


const route = {
    path: 'admin',
    canActivate: [() => inject(LoginService).isLoggedIn()]
  };

we created the entire guard in the guard declaration. The best thing about Functional Guards is that they are compostable.
 You can find an example of running router guards serially on GitHub.

6. The router unwraps default imports

To make the router simpler and reduce boilerplate further, the router now auto-unwraps default exports when lazy loading.

Let’s suppose you have the following LazyComponent:

 


@Component({
    standalone: true,
    template: '...'
  })
  export default class LazyComponent { ... }

Before this change, to lazy load a standalone component you had to:


{
    path: 'lazy',
    loadComponent: () => import('./lazy-file').then(m => m.LazyComponent),
  }

Now the router will look for a default export and if it finds it, use it automatically, which simplifies the route declaration to:


{
    path: 'lazy',
    loadComponent: () => import('./lazy-file'),
  }


7. Better stack traces


In Angular v15, now we can easily trace the code, it helps us when we face any error, so using stack trace we can find the place where the error is coming.


ERROR Error: Uncaught (in promise): Error
Error
   at app.component.ts:18:11
   at Generator.next (<anonymous>)
   at asyncGeneratorStep (asyncToGenerator.js:3:1)
   at _next (asyncToGenerator.js:25:1)
   at _ZoneDelegate.invoke (zone.js:372:26)
   at Object.onInvoke (core.mjs:26378:33)
   at _ZoneDelegate.invoke (zone.js:371:52)
   at Zone.run (zone.js:134:43)
   at zone.js:1275:36
   at _ZoneDelegate.invokeTask (zone.js:406:31)
   at resolvePromise (zone.js:1211:31)
   at zone.js:1118:17
   at zone.js:1134:33

So angular v15 developer team introduce this feature to trace more of a development code than showing libraries it calls.
In the previous version we have to give a lot of time to trace the error, but in v15 is easy to trace.
Below is the snippet for previous error indications:

 

  1. above error message coming from third-party dependencies (Angular framework, zone.js, and RxJS)
  2. we can see here no information was given about which user interaction encountered this bug. 

Now in Angular v15 stack trace will be like below

ERROR Error: Uncaught (in promise): Error
Error
   at app.component.ts:18:11
   at fetch (async)
   at (anonymous) (app.component.ts:4)
   at request (app.component.ts:4)
   at (anonymous) (app.component.ts:17)
   at submit (app.component.ts:15)
   at AppComponent_click_3_listener (app.component.html:4)

8. Stable MDC-based Components

Previously it was hard to reflector component-based angular material, but now it is possible by using MDC (Material design component for web)

In v15, majorly the refactoring work has been done in the DOM and CSS parts. Following the new update on responsiveness, there will be some styles in the old Angular applications that need adjustments, especially in the case of CSS overriding internal elements of the migrated components.

In v15, the old implementation of each new component is now deprecated, but still available from a “legacy” import

For example, we can retrieve the old mat-button implementation by importing its legacy button module.


import {MatLegacyButtonModule} from '@angular/material/legacy-button';




More improvements in components

In angular v15 couple of the user, observations are implemented  — range selection support in the slider.

To get a range input use

<mat-slider>

  <input matSliderStartThumb>

  <input matSliderEndThumb>

</mat-slider>

Additionally, all components now have an API to customize density which resolved another popular GitHub issue.

You can now specify the default density across all of your components by customizing your theme:

@use '@angular/material' as mat;



$theme: mat.define-light-theme((

  color: (

    primary: mat.define-palette(mat.$red-palette),

    accent: mat.define-palette(mat.$blue-palette),

  ),

  typography: mat.define-typography-config(),

  density: -2,

));



@include mat.all-component-themes($theme);

The new versions of the components include a wide range of accessibility improvements, including better contrast ratios, increased touch target sizes, and refined ARIA semantics.

 

9. CDK Listbox

CDK stands for Component Dev Kit gives different behavior primitives and helps in creating UI components. 

In the Angular v15, a new primitive called CDK Listbox was added, which helps developers to customize Listbox interactions drawn up by the WAI-ARIA Listbox pattern based on requirements..

CDK Listbox

Here, the behavioral interactions include keyboard interactions, bidi layout support, and focus management. No matter which one of them you use, each directive comes up with associated ARIA roles with respective host elements.

10. Extended esbuild support




In v14 having support for esbuild in ng build which enables faster build times and simplifies the pipeline.

Now v15 has experimental Sass, SVG template, file replacement, and ng build --watchsupport! 

Update esbuild in  angular.json 

From

"builder": "@angular-devkit/build-angular:browser"

to:

"builder": "@angular-devkit/build-angular:browser-esbuild"

 

 



------------------------------

Multi Select Dropdown In Angular 14

In this article, we will see how to implement a multi-select dropdown in Angular14 applications. 

Creating an Angular Application

Now let’s create an Angular application

ng new Angular14App        
  1. JavaScript
Copy





Now open the application in VS code and go to the package.json file, you will see the latest CLI and other install packages



Now open the terminal and Run the created Application using the below command

ng serve -o

and you will be navigated to http://localhost:4200/ URL and will see the below screen




Installing dropdown package


For using the multi-select dropdown, we have to use a package ng-multiselect-dropdown.
npm i ng-multiselect-dropdown



After installing the package now we have to add this module to our app. module file

Add NgMultiSelectDropDownModule.forRoot() in your import array of app module file.



Implement Multi-select dropdown

Go to the app.component.ts file and Create a local array of the items which we will show in the dropdown. 

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { IDropdownSettings } from 'ng-multiselect-dropdown';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dropdownData : any[] = [];  
  settings:IDropdownSettings={};
  form!:FormGroup;
  selectedItems: any[] = [] ;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.dropdownData = [
      { ID: 1, Value: 'Data1' },
      { ID: 2, Value: 'Data2' },
      { ID: 3, Value: 'Data3' },
      { ID: 4, Value: 'Data4' },
      { ID: 5, Value: 'Data5' }
    ];
    this.settings = {
      idField: 'ID',
      textField: 'Value',
    };
   
    this.form = this.fb.group({
      myItems: [this.selectedItems]
  });
  }
}

JavaScript
  1. JavaScript
Cop
Below is the app.component.ts file

<
div style="width:50%">
  <form [formGroup]="form">
    <ng-multiselect-dropdown
       [settings]="settings"
       [data]="dropdownData"
       formControlName="myItems">
    </ng-multiselect-dropdown>
  </form>
</div>
Markup

Now run your application and you will see output like below


Select default items on page load

When we run the application and want to load some dropdown values then we need to change app.component.ts file like below



import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { IDropdownSettings } from 'ng-multiselect-dropdown';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dropdownData : any[] = [];  
  settings:IDropdownSettings={};
  form!:FormGroup;
  selectedItems: any[] = [] ;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.dropdownData = [
      { ID: 1, Value: 'Data1' },
      { ID: 2, Value: 'Data2' },
      { ID: 3, Value: 'Data3' },
      { ID: 4, Value: 'Data4' },
      { ID: 5, Value: 'Data5' }
    ];
    this.settings = {
      idField: 'ID',
      textField: 'Value',
    };

    this.selectedItems = [
      { ID: 3, Value: 'Data4'  },
      { ID: 4,Value: 'Data5' }
    ];
    this.form = this.fb.group({
      myItems: [this.selectedItems]
  });
  }
}

JavaScript

  1. JavaScript
Cop

Now when you will run the application, you will see below the output.



Change the text of select all/ unselect all checkbox


If we want to change the text value of select all and unselectall then we need to change the dropdown setting like below
  ngOnInit() {
    this.dropdownData = [
      { ID: 1, Value: 'Data1' },
      { ID: 2, Value: 'Data2' },
      { ID: 3, Value: 'Data3' },
      { ID: 4, Value: 'Data4' },
      { ID: 5, Value: 'Data5' }
    ];
    this.settings = {
      idField: 'ID',
      textField: 'Value',
      selectAllText: "Select All Data",
      unSelectAllText: "UnSelect All Data",
    };
    this.selectedItems = [
      { ID: 3, Value: 'Data4'  },
      { ID: 4,Value: 'Data5' }
    ];
    this.form = this.fb.group({
      myItems: [this.selectedItems]
  });
  }
JavaScript


Output



Show hide select all options in the dropdown

If we want to hide or show the select all option then we need to change the dropdown setting like below
  ngOnInit() {
    this.dropdownData = [
      { ID: 1, Value: 'Data1' },
      { ID: 2, Value: 'Data2' },
      { ID: 3, Value: 'Data3' },
      { ID: 4, Value: 'Data4' },
      { ID: 5, Value: 'Data5' }
    ];
    this.settings = {
      idField: 'ID',
      textField: 'Value',
      enableCheckAll: false,
    };
    this.selectedItems = [
      { ID: 3, Value: 'Data4'  },
      { ID: 4,Value: 'Data5' }
    ];
    this.form = this.fb.group({
      myItems: [this.selectedItems]
  });
  }
JavaScript



Output


Add place holder

Whenever we see a dropdown, then we can add the placeholder to that, so let's change the dropdown setting like below

placeholder changes will be in app.component.html file


component file as shown in the below code.

<div style="width:50%">
  <form [formGroup]="form">
    <ng-multiselect-dropdown
       [settings]="settings"
       [data]="dropdownData"
       [placeholder]="'Select the Data'"
       formControlName="myItems">
    </ng-multiselect-dropdown>
  </form>
</div>
Markup

Output


Add search filter


Ng-multi select-dropdown by default gave a search filter for enabling this search filter you have to add a new setting in your settings array. 


ngOnInit() {
    this.dropdownData = [
      { ID: 1, Value: 'Data1' },
      { ID: 2, Value: 'Data2' },
      { ID: 3, Value: 'Data3' },
      { ID: 4, Value: 'Data4' },
      { ID: 5, Value: 'Data5' }
    ];
    this.settings = {
      idField: 'ID',
      textField: 'Value',    
      selectAllText: "Select All Data",
      unSelectAllText: "UnSelect All Data",
      allowSearchFilter: true
    };
    this.selectedItems = [
      { ID: 3, Value: 'Data4'  },
      { ID: 4,Value: 'Data5' }
    ];
    this.form = this.fb.group({
      myItems: [this.selectedItems]
  });
  }
JavaScript

Output


No Data Placeholder

For some reason when you call dynamic data from API and you get nothing to show then you have to tell the user that there is no data or something like that. 




    ngOnInit() {
   
    this.settings = {
      idField: 'ID',
      textField: 'Value',    
      selectAllText: "Select All Data",
      unSelectAllText: "UnSelect All Data",
      allowSearchFilter: true,
      noDataAvailablePlaceholderText: "Nothing to show data"
    };
   
    this.form = this.fb.group({
      myItems: [this.selectedItems]
  });
  }
JavaScript

Output

Callback Methods

  • onSelect - Return the selected item when an item is checked. Example : (onSelect)="onDataSelect($event)"
  • onSelectAll - Return the all items. Example : (onSelectAll)="onSelectAll($event)".
  • onUnSelect - Return the unselected item when an item is unchecked. Example : (onUnSelect)="onDataUnSelect($event)"
  • onFilterChange - Return the key press. Example : (onFilterChange)="onFilterChange($event)"
  • onDropDownClose- Example : (onDropDownClose)="onDropDownClose()"

Here are some examples of callback methods.

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { IDropdownSettings } from 'ng-multiselect-dropdown';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dropdownData : any[] = [];  
  settings:IDropdownSettings={};
  form!:FormGroup;
  selectedItems: any[] = [] ;
 
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.dropdownData = [
      { ID: 1, Value: 'Data1' },
      { ID: 2, Value: 'Data2' },
      { ID: 3, Value: 'Data3' },
      { ID: 4, Value: 'Data4' },
      { ID: 5, Value: 'Data5' }
    ];
    this.settings = {
      idField: 'ID',
      textField: 'Value',    
      selectAllText: "Select All Data",
      unSelectAllText: "UnSelect All Data",
      allowSearchFilter: true,
      noDataAvailablePlaceholderText: "Nothing to show data"
    };
    this.selectedItems = [
      { ID: 3, Value: 'Data4'  },
      { ID: 4,Value: 'Data5' }
    ];
    this.form = this.fb.group({
      myItems: [this.selectedItems]
  });
  }

  onDataSelect(item: any) {
    console.log('onData Select', item);
  }
  onDataUnSelect(item: any) {
    console.log('onData UnSelect', item);
  }
  onSelectAll(items: any) {
    console.log('onSelect All', items);
  }
  onUnSelectAll() {
    console.log('onUnSelect All fires');
  }
}

JavaScript
<div style="width:50%">
  <form [formGroup]="form">
    <ng-multiselect-dropdown
       [settings]="settings"
       [data]="dropdownData"
   
       formControlName="myItems"
       (onSelect)="onDataSelect($event)"
       (onSelectAll)="onSelectAll($event)"
       (onDeSelect)="onDataUnSelect($event)"
       (onDeSelectAll)="onUnSelectAll()">
    </ng-multiselect-dropdown>
  </form>
</div>
Markup

Output


In the above image, we can see, that we performed a couple of callback operations and the same are logged in the console.









---------------------------------------------------