Showing posts with label angular development. Show all posts
Showing posts with label angular development. Show all posts

Friday, September 3, 2021

Top 10 Concepts To Know For Angular Developer

 

Top 10 Concepts To Know For Angular Developer

Angular is one of the biggest frameworks that provides lots of features. It seems to be always changing and updating but in reality there are certain things that remain the same. There are some concepts that you need to learn when it comes to Angular in order to efficiently use the javascript framework. Lot of us get stuck because we don’t know where to go or what to search for. Here we came up with some concepts that you should master to be an angular developer. Let’s have a look at those important concepts.

Also know the new features of Angular 12.2 at- What’s New In Angular 12.2?

Top 10 Concepts To Master To Become Angular Developer-

1. Modular Angular Architecture-

Angular’s module architecture is unique and probably one of the hardest part for beginners to grasp. It’s most confusing concept is that we’re already using a module architecture on top of it. As angular modules add a layer of logical grouping, it is vital to keep them as much related as possible. Whereas knowing how to separate and split functionality  of an application in well-defined modules is a fundamental part of architecting angular apps. There are 5 different types of Angular modules that you should be aware of:

  • Service Module
  • Routing Module
  • Declarations/Widget Module(module that is a collection of UI components, directives and pipes)
  • Domain/Feature Module
  • Core/Shared Module

2. Routing-

Routing allows you to organize SPA into various virtual pages and load app’s packages on-demand. This is all because of Angualr’s lazy loading features. If you work on large app and packages exceed 1MB, you came to the importance of this. In fact no one wants to download that high amount of data to interact with your app. Routing should be used to split top-level routing and drive smaller and deeper parts of UI. It allows to split content of package into primary routes and smaller parts of app that don’t need to be downloaded on your user’s devices until they’re requested.

3. Forms And Validation-

Most CRUD applications are made up of various forms. You maybe spend more time writing forms and hence it is important to learn angular forms. Most of forms should probably be using ReactiveFormsModule module and do please ditch two-way data binding with ngModel unless you have one simple control. Angular Forms API is easy to understand and adapting it properly is important. One of the main pitfall to be aware of is that it is basically untyped. Might be it is the most annoying part so you should be very careful to ensure your forms are adhering to your data structure’s types.  

With forms validation also come. Learning how validators work in conjunction with CSS will help you to speed up workflow and turn your app into error-handling ready space.

Also know the – Awesome Steps To Make Your Angular Form Reactive

4. State Management With RxJs-

State of the app determines the data that is displayed to your user. If the state is complex, chances are that your complete data structure will turn flaky and crumble against any changes. When you start to know how states work in Angular, you will be able to understand how and why your data behaves the way it is. While Angular has its own state management system, RxJs is an incredible method for centralizing states and its related data. Data can get lost in the chain of parent-child relationships. RxJs decouples this by creating a centralized store.

5. Change Detection-

Angular makes use of default change detection strategy meaning that components will always be checked. While there’s nothing wrong with using the default, it tends to be a wasteful method to detect change. For small scale apps, performance and speed are alright. But when app gets to a particular size, things can become quite heavy to run, particularly in old browsers.

onPush change detection strategy will speed up app because it depends on particular triggers to occur instead of constant check to see if anything has happened.

In order to master change detection, it is important to start with following-

  • Use only observables to display data in your templates. If you’re using local state, use a BehaviorSubject
  • Treat all data as immutable- using Rx, Powered State Management libraries helps in this

Mastering change detection is important and necessary step towards building extremely performant applications:

  • You need to ensure to update when required 

6. Separation Of Concerns Between Components, Services, And Directives-

Separating concerns looks simple in theory but harder than it seems. We’ve been instructed since the Angular.js days to keep components “lean” and services “fat”, and generally there hasn’t been a significant difference in the most current versions. Still it is important to deeply understand what exactly belongs into Components and what belongs into Services, and why Directives may only be an underrated feature.

State-

State placing is a matter of understanding whether data is accessed and shared outside of a component or whether it is local and encapsulated. 

  • If the state is local and used only within a component, then simply store it in a component
  • If the state is shared between components, place your state in a service. It doesn’t matter what state management tool you use.

DOM Manipulation-

Many DOM manipulation should happen within Directives. Let’s consider that you’re implementing drag and drop functionality to components.

Definitely, you can create a component and bind events, but at such a way, you’re mixing two things:

  • how the component looks
  • how a certain component’s feature behaves

Directive are reusability feature in Angular and it can be used to take off lots of responsibility from components.

7. Smart/Dumb Component Architecture-

While building angular apps, you might put everything into components. But it is not a best practice. Main idea of smart/dumb components in Angular is that needs to be talked about more, particularly in beginners community. Regardless of whether a component is smart/dumb determines its role in the scheme of the application. Mostly Dumb components are stateless with behaviors that are simple to predict and understand. Ensure your component dumb whenever possible.

Smart components are difficult to grasp because inputs and outputs are included. So as to appropriately use Angular’s capabilities, look into smart/dumb component architecture. It will give you patterns and mindsets on how to work with your code and its relationships with each other.

8. Route Guards, Pre-loads, Lazy-loading-

If you’ve login of some kind, you need route guards. Concept is that, in many apps, you can protect particular views from unauthorized views is an important requirement. Route guards acts as an interface between the router and the requested route. It is the decision maker that decides whether a specific route is allowed access or not. There is lot to explore about route guards- routing decisions based on things such as token expiration, user roles authentications and route securities.

Pre-loads and lazy loading can improve your user’s experience by improving app’s load time. Also keep in mind that, pre-loads and lazy-loading are more than only deciding if you’re going to load a specific set of images or not. It improves bundled architectures and load different parts of app which may exist on different scopes and domains.

Thursday, August 27, 2020

Top 15 Angular Component Libraries In 2020

 

Top 15 Angular Component Libraries In 2020

Top 15 Angular Component Libraries In 2020

Angular is considered as one of the most simple and popular front end framework around the globe. Created by Google and initially released 5 years ago, this open-source programming tool has won the hearts of developers from all over the world. With strong community support and rich functionality, Angular allows developers to provide the seamless user experience and consistency over all devices and platforms from tablet to more. Moreover, either beginners or experienced- can access various Angular advantages. It allows developers to use components in a manner that the UI remains separated as a standalone entity and reusable parts. Here you’ll see the top 15 Angular components to produce a great software solution easily and rapidly.

Top 15 Angular Component Libraries In 2020

1. Angular Material-

Angular Material components was earlier known as Material2 and is a component library that implements the material design of Google. It was built using TypeScript and Angular. These UI components follow the best practices of the Angular Developer when composing the Angular code. So as to generate various templates from the command line, you can rapidly add a new feature. Various components are added like Badge for element status, Tree for data rendering and Bottom-Sheet service for interaction with panel display.

Some of the popular angular components that you can use for angular project are-

  • Progress Spinner, Icon, Chips, Buttons, Progress Bar
  • Create popups like  Dialog, Tooltip, Snackbar,
  • Control forms like Datepicker, Checkbox, AutoComplete, Form field, Radio button, Input, Slider, Select and Slide Toggle.
  • Layout Components like Grid List, Cars, Tabs, Stepper, List, Expansion Panel
  • ToolBar menu, Side Navigation and the navigation bar
  • Data table format

2. NG Bootstrap-

It offers Bootstrap 4 components for Angular and thusly it has replaced Angular-UI bootstrap. It doesn’t have any external dependencies while it offers high testing coverage. Using appropriate HTML elements with aria attributes, here all its widgets will become accessible. Here is a list of bootstrap components that can be used are-

  • Typehead
  • Datepicker
  • Tooltip
  • Popover
  • Modal
  • Carousel

3. NG Lightning-

The main goal of introducing NG Lightning library is to provide directives and native components for the Salesforce Lightning Design System. When you implement this component in your angular app, it significantly impacts on flexibility and performance also.  The list of NG-Lightning components is as follows-  

  • Breadcrumbs
  • Buttons
  • Badges
  • Icons
  • Datatables
  • Ratings
  • Lookups
  • Spinners

4. NGX Bootstrap-

It is an open-source MIT Licensed project that provides various components, powered by Angular. It involves alerts, taps, buttons, pagination, popover, progress bar, and so on. Interactive elements like  dropdown menus, modal dialogs, custom tooltips are planned to work for touch, mouse, and keyboard users. Thus web developers don’t need to use original JavaScript components. Rather, they can drop into their applications Markup and CSS released by Bootstrap. Ngx-bootstrap is continually being improved with more than 5000 stars on GitHub.

5. NG2 Charts-

It includes charts for Angular2 based on Chart.js. Being MIT licensed Angular project, the library is available in both dark and light themes. It provides one directive — baseChart for all chart types, and 8 types of charts: line, pie, bar, polarArea, radar, bubble, scatter etc. It has nearly 1700 stars on GitHub.

6. PrimeNG-

It is a set of 80+ UI components that comes with various themes that are from flat to material design. It is very simple to utilize and customize the components of PrimeNG as they are designed expertly. Mobile UX comes with responsive and touch optimized layouts. You can use simple to complex elements like graphs, tables, sliders and pop-ups. Big brands like Fox and eBay use this library. Library components that PrimeNG supports are as follows-

  • Messages and Growl for message alert
  • Overlay components like Dialog, Lightbox, Overlay Panel.
  • File Upload Component
  • SplitButton and Buttons component.
  • Charts that come with the optimized option of Radar, Bar, Line, Doughnut, Pie.
  • Toolbar, Accordion, ScrollPanel, Card, TabView panel components
  • Data Components in DataList, DataTable, DataGrid, Tree Table format.

7. Clarity-

Clarity is an open-source Angular component library to bring Angular components, UX guidelines and HTML/CSS framework together. Use this component to take advantage of a rich set of performant components and data-bound on top of Angular. Have a look at Clarity components-

  • Login Page
  • Progress Bars
  • Passwords
  • Alerts
  • Grid
  • Radio Buttons
  • Signposts
  • Tree View
  • Toggle Switches
  • Wizards

8. Onsen UI-

Onsen UI is a well known library for mobile web apps and hybrid apps for iOS and Android by using JavaScript. It offers components with Material and Flat designs and comes with binding for Angular. It offers automatic styling according to the platform you need for your project. Some of the Onsen UI components are:

  • Side Menu
  • Tabs
  • Lists and forms
  • Stack Navigation
  • Automatic Styling

9. Vaadin Components-

Vaadin provides material inspired UI components for web and mobile applications, that helps to bridge the gap between Polymer elements and Angular components. Here the components are kept in various repos even when they are grouped as a single one as you can discover separately on Bit. So as to improve experience for sharing the codes between the developers and applications, the library integrates Git, package managers, and different tools. It helps you to take all the pressure outside your codes as it will let you with codeshare by reusing or sharing components without configurations or refactoring.

Some of the free and premium version components you can have for it are as:

  • CRUD
  • Context Menu
  • Spreadsheet
  • Combo Box
  • Password Field
  • Custom Field
  • Progress Bar
  • Rich text Editor
  • Notification
  • Charts

10. Nebular-

It is an Angular 8 UI library with a focus on attractive design and ability to  easily adapt it to your  brand. It has 4 attractive visual themes, a powerful theming engine with runtime switching and support of custom css properties mode. Useful nebular components for you are as follows-

  • Navigation (Sidebar, Menu, Tabs, Actions)
  • Forms (Input, Button, Checkbox, Toggle, Radio, Select, Datepicker)
  • Global (Layout, Card, Flip Card, Stepper, Accordion, List, Infinite List)
  • Modals & Overlays (Popover, Context Menu, Dialog, Toastr, Tooltip, Window)
  • Extra (Global Search, User, Alert, Icon, Spinner, Progress Bar, Badge, Chat UI, Calendar)
  • Data Table (Tree Grid)
  • CDK (Сalendar Kit)

Right now, Nebular has 5,903 stars on GitHub.

11. Angular Google Maps-


Wednesday, August 19, 2020

Top 11 Angular Best Practices To Follow In 2020

 

Top 11 Angular Best Practices To Follow In 2020

Top 11 angular best practices to follow in 2020

Today, more than 40% of front-end developers use Angular. It is a prominent JavaScript framework for developing dynamic mobile and desktop web applications. Angular is developed and maintained by Google itself. It has gained immediate popularity and support as now static HTML pages could be more interactive. Here we have listed some of the new angular practices that will help you to write clean code, maintain coding standard and performance.

Top 11 Angular Best Practices

Angular Best Practices

1. Use Angular CLI-

It is a powerful accessibility tool available for developing apps with angular. Angular CLI eases the app development and follows all best practices. Angular CLI is a command-line interface tool which is used to initialize, develop, scaffold, maintain and test-debug angular apps. Use Angular CLI to generate new components, directives, modules, services and pipes rather than manually creating files and folders.

# Install Angular CLI
npm install -g @angular/cli
# Check Angular CLI version
ng version

2. Angular Coding Styles-

For angular web development, you should follow the standard coding format and your project must have a clean coding style which will in general be basic, understandable and adaptable by your programmer in future. Here are some rules that you should follow-

  • Limit files to 400 lines of code
  • Per function, the code must not exceed from 75 lines
  • Use custom prefix to share feature area for all slider components
  • Have consistent names for all symbols. The suggested pattern is feature.type.ts
  • If the values of the variables are intact, then declare it with ‘const’.
  • If you often prefix names for field, table, and database, then you need to avoid this for Interface names like iShape, AbastractShape, etc.
  • Use dash to separate words in descriptive name and use dots to separate descriptive name from the type
  • Names of properties and methods should be in lower camel case
  • Leave one empty line between imports and modules like third party and application imports, third party modules and custom modules.

3. Follow Proper Folder Structure-

Creating a folder structure is an important factor to consider before project initialization. A messy folder welcomes many problems which continue frequenting you all through your development process. Regardless of whether it is a medium and large-sized project,  you will go over a lot of changes being developed and your project should easily adapt the new changes made in the middle of development. And, that is possible when you have made an appropriate folder in place.

-- app
|-- modules
|-- home
|-- [+] components
|-- [+] pages
|-- home-routing.module.ts
|-- home.module.ts
|-- core
|-- [+] authentication
|-- [+] footer
|-- [+] guards
|-- [+] http
|-- [+] interceptors
|-- [+] mocks
|-- [+] services
|-- [+] header
|-- core.module.ts
|-- ensureModuleLoadedOnceGuard.ts
|-- logger.service.ts
|
|-- shared
|-- [+] components
|-- [+] directives
|-- [+] pipes
|-- [+] models
|
|-- [+] configs
|-- assets
|-- scss
|-- [+] partials
|-- _base.scss
|-- styles.scss

4. Use Index.ts-

Index.ts is helpful to keep related things together with the goal that we don’t need to be bothered about the source file name. It helps to reduce the size of import statement. Let us see an example-

We need /heroes/index.ts as-

//heroes/index.ts
export * from './hero.model';
export * from './hero.service';
export { HeroComponent } from './hero.component';

You can import all things by using source folder name.

import { Hero, HeroService } from '../heroes'; // index is implied

5. Lazy Loading Feature Module-

Using lazy load the modules can improve your productivity. It is a built-in feature in Angular that helps developers to load the required things. For instance- When you use the feature, it loads the components and other things that you need and stops unnecessary files to get loaded.

Here’s how it functions;

// app.routing.ts
{ path: 'not-lazy-loaded', component: NotLazyLoadedComponent }

Here the ‘LazyLoading’ isn’t set up and you will wind up making large and superfluously heavy-sized applications.

When you use ‘LazyLoad’ and it reduces the size of the application by abstaining from unnecessary file from loading.

6. Use ES6 Features-

ECMAScript is updated with new features and functionalities. Use ES6 that  has a lot of new features and functionalities which could be used in Angular. 

New features of ES6-

  • Arrow Functions
  • String interpolation
  • Object Literals
  • Let and Const
  • Destructuring
  • Default

Using ‘let and const’ instead of ‘var’-

Using ‘let and const‘ instead of ‘var’ prevents the issues and problems which you have due to var. ‘let’can be used in a normal situation and the value does not receive any changes, then ‘const’ should be in place. Here’s the example;

let temp;
Const pi = 3.14159

7. State Management-

It manages the state transitions by storing the states of any form of data. NGRX, NGXS, Akita, are some of the state management libraries with different usages, states and purposes. NGXS could be the preferred and easy to learn for developers. 

8. Avoid Logic In Templates-

All template logic will be extracted into a component which helps to cover that in a unit test and reduce bugs when there is template change.

Logic in templates

// template
Status: Unavailable// component
ngOnInit (): void {
this.status = apiRes.status;
}

Logic in component

// template
Status: Unavailable// component
ngOnInit (): void {
this.status = apiRes.status;
this.isUnavailable = this.status === 'inActive' || 'hold';
}

9. Use async pipe In Templates-

Rather than using plain JS values, observables can be directly used in templates with async pipe. An observable would be unwrapped into plain value. When a component using the template is destroyed, observable is automatically unsubscribed.

Without Using async pipe

//template
{{ text }}

Using async pipe

// template
{{ text | async }}
// component
this.text = observable.pipe(
map(value => value.item)
);

10. Use trackBy With ngFor-

When you are going to use ngFor to loop over an array, use it with a trackBy function that returns a unique identifier for each DOM item. When the array changes, angular re-renders the whole DOM tree. But when you use trackBy, angular will know which element has changed and will only make DOM changes only for that element.

Use ngFor

<li *ngFor="let item of itemList;">{{item.id}}</li>

Now whenever changes occur, the whole DOM tree will be re-rendered.

Using trackBy function

<ul>
  <li *ngFor="let item of itemList; trackBy: trackByFn">
    {{item.id}}
  </li>
</ul>
Load items(button)
export class MyApp {
getItems() { // load more items }
trackByFn(index, item) {
return index; // or item.id
}
}

Now, it returns as a unique identifier for each item, hence just updated items will be re-rendered.  

11. Declare Variable Type Instead Of Using ‘any’-

Generally when developers work on Angular projects, they use ‘any’ to declare variables. If you are not specifying the variables and constants, they will be assumed by the value and thus, will be assigned to it. If it occurs, you are now in a problem as it will create some unintended issues, anytime. 

For instance;

If you code like this;

const x = 1;
const y = 'a';
const z = x + y;
console.log(`Value of z is: ${z}`

// Output
Value of z is 1a

You are supposed to perfect output.

And, if you code like this;

const x: number = 1;
const y: number = 'a';
const z: number = x + y;

// This will give a compile error saying:

Type ‘”a”‘ is not assignable to type ‘number’.

const y: number

You may not get all you needed. To put it plainly, you can prevent this by typing the number instead of typing ‘any’.

Know the new features and updates of Angular 10 at- Amazing New Features And Updates Of Angular 10.

Final Words-

Application development needs proper attention to make it successful and popular. Effective development with best practices helps you to achieve the goal you want to. Apart from the above mentioned best practices, there are plenty of others that you get through your experience.

If you are thinking to develop an app with angular, connect with solace experts. You can hire angular developers of Solace team to help you through development. Connect with solace and get a free quote for effective and efficient app development. We will be happy to help you.

Tuesday, November 26, 2019

Awesome Steps To Make Your Angular Form Reactive

Forms in Angular-

Angular provides two primary ways to deal with forms- the template driven method and also the model- driven method which includes reactive forms. The template method is the default method of form handling in Angular where you need to utilize ng directives to build your form in the template. It is great for simple forms like basic contact forms in brand pages. It draws a lot of similarities to the old Angular JS way of form handling and also implicitly creates concepts like form control behind the scenes. The other approach is the reactive forms approach.

What are reactive forms?

Reactive forms are a platform for achieving the model-driven approach of form handling in Angular. After the release of Angular 2, Angular introduced it. In spite of the fact that it is apparently verbose, it is the most powerful and also scalable way of form handling in Angular. Rather than the template driven forms that use template directives to build the skeleton of a forms, reactive forms let you build out a form and react to the changes in the values inside the component class.

Why are reactive forms important?

With reactive forms, you discover that it is simpler to build cleaner forms as each JavaScript framework advises not to make the template clustered, this is a priority as the form logic lies in the component class. Also, it reduces the requirement for using a lot of directives and even end-to-end testing as you can now effectively test your forms. It also gives the developer all of the control and nothing is implicit anymore. Each choice about inputs and controls has to be made purposefully and, obviously, explicitly.

Steps To Make Your Angular Form Reactive-

1. Registration of reactive forms-

The initial step is to tell Angular you want to use reactive forms by importing the module and also registering it under imports. Your app.module.ts file should look like this:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployerComponent } from './employer/employer.component';
import { EmployeeComponent } from './employee/employee.component';
@NgModule({
  declarations: [
    AppComponent,
    EmployerComponent,
    EmployeeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. Form controls-

Form controls are classes that can hold both the data values and also the validation information of any form element. In other words, each form input you have in a reactive form should be bound by a form control. They are the basic units that make up reactive forms. To use form controls, you need to import the module into the component you need to make your reactive form in. Open your employer.component.ts file and copy this code block inside it:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms'
@Component({
  selector: 'app-employer',
  templateUrl: './employer.component.html',
  styleUrls: ['./employer.component.css']
})
export class EmployerComponent implements OnInit {
  position = new FormControl('');
constructor() { }
ngOnInit() {
  }
}
Here the form control was imported. And also inside the class it was instantiated with the constructor for position. To reflect it in the interface, you have guaranteed that you associate it with the input element in the template.
// copy into employer.component.html file
<label>
  Position
  <input type="text" [formControl]="position">
</label>
To display it, open your app.component.html file and paste in the code block below:
<div style="text-align:center">
  <h2>Angular Job Board </h2>
  <app-employer></app-employer>
</div>

3. Data binding in reactive forms-

At this stage, you probably won’t see any enormous difference between this and the ordinary template forms you are used to, but it begins to make a lot of sense when you need to start dealing with the data values you get from your form. For data interpolation review how you should use ng-bind directive to bind properties to values in the template. Now all you should simply to call the value and the reactive forms API will bind the data and also display it for you.
<label>
  Position
  <input type="text" [formControl]="position">
</label>
<p>
  Your response: {{ position.value }}
</p>
With just property.value, a snapshot of the data value at the given time is captured and also displayed in the interface.

4. Replacing a data value-

There are a lot of the more things you can accomplish with the form control properties and also methods inside the reactive forms API. Look at the, at updating a data value with new data. The previously mentioned API gives a method called setValue(). To set data values for input elements, this method is used. The syntax as follows:
callingFunction() {
 this. propertyName.setValue('new data value');
}
To execute it in your sample demo form, you will add a replace data button in the template to trigger the function so that the data value can be updated. In your employer.component.ts file, copy in the code block below:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms'
@Component({
  selector: 'app-employer',
  templateUrl: './employer.component.html',
  styleUrls: ['./employer.component.css']
})
export class EmployerComponent implements OnInit {
  position = new FormControl('');
constructor() { }
ngOnInit() {
  }
  callingFunction() {
    this.position.setValue('backend engineer');
   }
}
Now in the employer.component.ts file copy in the code block below:
<label>
  Position
  <input type="text" [formControl]="position">
</label>
<p>
  Your response: {{ position.value }}
</p>
<p>
  <button (click)="callingFunction()">Replace Data</button>
</p>
You will see it seamlessly replaces the data value on click as you determined.

Conclusion-

This is a “beginning” guide for utilizing reactive forms in Angular, you were shown the different approaches of form handling (and the differences of the approaches). You were also shown how the reactive forms approach is significant and more effective and how it encourages to write cleaner code. 
If you are still confused to build reactive forms, kindly reach to the solace experts team. Team will surely help you through their knowledge. They are well proficient in new technologies and also trends to give you the best solution.