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

Monday, January 24, 2022

How To Secure Angular Apps?

 

How to secure angular apps

We all know that, AngularJS is an open-source front-end javascript framework and it provides convenient data binding options on client-side and. It allows developers to decouple HTML templates, leading to smoother development. AngularJS has some security features such as automatic output encoding, supports strict contextual escaping and has in-built content security policy but still it has its own issues that should be taken care of. Generally angularjs uses inline styles that can be easily bypassed by hackers through custom injected content. If you’re going to use AngularJS for your next project, then you must know how to secure angular apps. Here we’ll discuss about 10 best practices to secure angularjs app. Let’s see each one in detail.

10 Tips To Secure AngularJS App-

Angular logo

1. Prevent Apps From Cross-site scripting(XSS)-

XSS allows hackers to add client-side script or malicious code into web pages that can be viewed by users. Mostly such attacks happened through query string, input field, request headers. To prevent XSS attack, we must present a user to enter malicious code from DOM. For instance, attacker can enter some script tag to input field and that might render as read-only text. When values are inserted into DOM through attribute, interpolation, properties etc. by default, Angular considers all values as untrusted. It escapes and sanitizes values before render. XSS related security in Angular defined in “BrowserModule”. DomSanitizer helps to clean untrusted parts of value. DomSanitizer class looks like-

export declare abstract class DomSanitizer implements Sanitizer {
 abstract sanitize(context: SecurityContext, value: SafeValue | string | null): string | null;
 abstract bypassSecurityTrustHtml(value: string): SafeHtml;
 abstract bypassSecurityTrustStyle(value: string): SafeStyle;
 abstract bypassSecurityTrustScript(value: string): SafeScript;
 abstract bypassSecurityTrustUrl(value: string): SafeUrl;
 abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl;
}

There are two types of method patterns: sanitize and bypassSecurityTrustX (bypassSecurityTrustHtml, bypassSecurityTrustStyle, etc.). Sanitize method gets untrusted value from context and returns trusted value.

The bypassSecurityTrustX methods gets untrusted values from context and as per the value usage it returns a trusted value. In a particular condition, you may need to disable sanitization. After setting any one bypassSecurityTrustX methods, you can bypass security and binding the value.

Example

import {BrowserModule, DomSanitizer} from '@angular/platform-browser'

@Component({
 selector: test-Component',
 template: `
 <div [innerHtml]="myHtml"></div>
 `,
})
export class App {
public myHtml: string;
 constructor(private sanitizer: DomSanitizer) {
 this. myHtml = sanitizer.bypassSecurityTrustHtml('<h1>Example: Dom Sanitizer: Trusted HTML </h1>') ;
 }
}

Always be careful whenever you trun-off or bypass any security setting that might malicious code and we might inject a security vulnerability to the app. Sanitization inspect untrusted values and convert it to a value which is safe to insert into DOM tree. It doesn’t change value at all time and angular allows untrusted values for HTML, Styles and URLs. Here are some of the security contexts defined by Angular-

  • It makes use of HTML context when interrupting value as HTML
  • Uses Style context when any CSS bind into a style property
  • When bind URL, it uses URL context

Also know- Top 10 Concepts To Know For Angular Developer

2. Use Security Blinters-

Programmers can take an advantage of security linters to perform basic static code analysis and provide red flags for errors, bugs or security vulnerabilities. In AngularJS, we are talking about ‘eslint-plugin-scanjs-rules’a nd ‘eslint-plugin-angular’ that helps in general coding conventions, rules and guidelines about security.

Know more


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

&lt;li *ngFor="let item of itemList;"&gt;{{item.id}}&lt;/li&gt;

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

Using trackBy function

&lt;ul&gt;
  &lt;li *ngFor="let item of itemList; trackBy: trackByFn"&gt;
    {{item.id}}
  &lt;/li&gt;
&lt;/ul&gt;
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.