The best programming tricks you need to learn now

Programming is one of the most creative jobs to do. To be a good programmer, learning new tricks and being compatible with the changes in programming field is quite necessary. On daily basis, different rules and modifications are introduced in the field of programming. There is always some programming tricks you need to learn in the field of programming. New challenges always come and go in the field of programming. To be a good programmer all these challenges need to faced with proper dedication and creativity. Read the blog below to know best programming tricks.

The-best-programming-tricks-you-need-to-learn-now

Readability

Comments are an important aspect of the readability. Understanding a code after some period of time becomes quite difficult, however with the use of appropriate comments, you can reuse your code. It guarantees fast debugging and designing of your code. Once people get to know your code, they start to know you as a programmer. It is a mistake that difficulty gives your code a weird look. The reality is that difficult things coded in an easy manner are the best feeling.

You will appreciate easy programs when you identify an error. Readability assists you cross-check code without getting a headache. Everyone experiences errors in their own manner. Readability comes into play when you can present your code in the programming languages.

Express your program code in such a manner that your colleagues can understand it easily. If you have a client project, readability will play a crucial role in customer satisfaction. According to the experts, readability always has an upper hand over the unreadable code.

Client Dealings

In order to become a good programmer, the important thing to grasp is the client’s engagement or interaction. The whole bunch of requirements of clients may be unknown to your team lead or the manager. It is your accountability to provoke requirements from clients as you move ahead in your project. Give a suitable platform for the client to engage with you easily.

Discuss thoroughly that may help them to recall their requirements. There is more than one technique of doing a particular task. Dealing with clients on the continuous basis can guarantee fulfillment of all requirements. Be confident about your work and interact more with your customers. The code written helps the client to get their needs fulfilled.

Grow your Network

Go to seminars and meetings. Interact with other programmers to know the programming tricks, guidelines, and rules. At the least, you will have new colleagues; at the most, you can be in touch with experts who are ready to train you. In learning anything, networking is an important asset for an expert programmer. Try to be active on social media platforms, for instance, LinkedIn is an amazing platform to manage your professional network. Be skilled with the several programming languages in multiple domains. Take part in quiz, competitions and other programming events to boost your programming skills and tricks. Technical brilliance and good design are the features of a great programmer. Ensure you continue them.

Keep learning

Learning is the best programming trick, being a student always is the best thing to learn anything. Life gives you a number of things to learn. Always be active on your personal activities like reading books, playing games and taking part in outings. Always sharpen your skills, reflexives and stay up to date with the changing world. Always try to add something new to your skills. Don’t try to indulge in multiple things at a single time, get updates on new languages and frameworks, and get to know about their basics. Learning ensures you are updating your skills and getting new programming tricks.

Take initiative to learn on new projects on regular basis. Take these projects seriously, always treat them as a challenge and as a chance to further enhance your programming skills into long-term memory. As a programmer adapt quickly to changing requirements. When requirements vary, the tricks to code vary too. Adaptiveness is the important skill to be a good programmer.

Author’s bio:

I am a professional content writer since 2011 working with SEO Services Company Delhi and the graduate of the English with a degree in Mass Communication. My written blogs and articles have been published in several online publications. I am fond of writing, reading, traveling, and Internet surfing.  

 

Set the Default Value to Select in Angular 5 iterated with Array of Objects

Here, the simple and easy way to set default value to select in Angular 5 which is iterated with an array of objects.

Let’s consider the below sample object which is going to iterate in the select options

[
      {
		"userName": "User1",
		"userId": "1",
		"userRole": "admin"
	},
	{
		"userName": "User2",
		"userId": "2",
		"userRole": "moderator"
	},
	{
		"userName": "User3",
		"userId": "3",
		"userRole": "user"
	}
]

In above array, I need to iterate and get the complete object on selection. So I assign the complete object to the [ngValue] to the iterative option tag.

While changing the option you will get the proper object’s value, but in case of retrieving & reassign the data or initialize some value to the select dropdown as default, we cant able to straightaway do that by assigning the appropriate object to the select’s ngModel.

Solution to set default value to select in Angular 5.

HTML :

For that, we can use [compareWith].  Refer the below HTML code snippet having the [compareWith ] directive.

 <select [compareWith]="compareByuserId" [(ngModel)]="selectedUser" name="user" (change)="setUserData(selectedUser)">
    <option disabled value="undefined" > Select User</option>
    <ng-container *ngIf="users" >
       <option *ngFor=" let user of users" [ngValue]="attribute" >{{user.userName}} </option >
     </ng-container >
</select >

TypeScript:

Add the below-given code snippet to your respective TS file. Here userId is the key which used to compare the available and assigned object. You can change the key on demand.

 compareByuserId(arg1, arg2) {
    if (arg1 && arg2) {
      return arg1.userId== arg2.userId;
    } else {
      return false;
    }
  }

Retrieve & Assign Value:

Now you can directly assign the required object to the ngModel selectedUser.

This will make the select box to have the assigned value as the preselected as default.

Assign the undefined to selectedUser have the select box to have the “Select User” as a default selection.

Tune In for more Angular updates.

Consolidated list of angular cli commands

Using angular cli commands you can easily scaffold and build the angular application. Here I list and discuss the commands available in angular cli. As you know Angular development approach changes and the architecture got numerous improvements after the latest release.  Along with that the angular/cli also upgrade to support the modern angular javascript framework.

angular cli commands

angular/cli

angular/cli is a tool that helps you to start, build and test you angular application easily. angular/cli uses several commands to initialize, scaffold and maintain the application. Let’s see the most commonly used commands while creating the angular application. Before starting you need to install the angular/cli package.

Note:npm uninstall -g angular-cli @angular/cli && npm cache clean && npm install –save-dev @angular/cli@latest

Consolidated list of angular cli commands

angular/cli action

Command

Shortened

New Applicationng new app-nameng new app-name
Create Componentng generate component component-nameng g c component-name
Create Directiveng generate directive directive-nameng g d directive-name
Create Pipeng generate pipe pipe-nameng g p pipe-name
Create Serviceng generate service service-nameng g s service-name
Create Classng generate class class-nameng g cl class-name
Create Guardng generate guard guard-nameng g g guard-name
Create Interfaceng generate interface interface-nameng g i interface-name
Create Enumng generate enum enum-nameng g e enum-name
Create Moduleng generate module module-nameng g m module-name
Lint using tslintng lintng lint
Build & run unit testng testng test
Run end to end testng e2eng e2e
Compile application to output Dirng build (–dev/–prod)ng build (–dev/–prod)
Eject app and create proper webpack configuration and script bundleng ejectng eject
Extract localization i18n message from templateng xi18nng xi18n
Build and start web serverng serveng serve

The above mentioned are the basic angular/cli commands. You can also use options as a parameter along with the commands to narrow down the required behavior of cli.

Upgrade Application from Angular 2 to Angular 4

Angular 2 to Angular 4 upgrade is much easier than you imagine. Minimal changes in your package.json and tsconfig.json is enough to run your app developed in angular 2.  As Angular has backward compatibility which runs previous release apps in the new upgraded version.

angular 2 to angualr 4

Angular 2 to Angular 4

Pakage.json changes

angular 2 to angular 4

For upgrade, just change the “Dependencies” & “devDependencies ” portion of the package.json

Upgraded Package.json content.

"dependencies": {
        "@angular/common": "^4.0.0",
        "@angular/compiler": "^4.0.0",
        "@angular/core": "^4.0.0",
        "@angular/forms": "^4.0.0",
        "@angular/http": "^4.0.0",
        "@angular/platform-browser": "^4.0.0",
        "@angular/platform-browser-dynamic": "^4.0.0",
        "@angular/router": "^4.0.0",
        "core-js": "^2.4.1",
        "rxjs": "^5.2.0",
        "systemjs": "^0.19.47",
        "zone.js": "^0.8.5"
    },
    "devDependencies": {
        "@types/node": "^6.0.60",
        "concurrently": "^3.1.0",
        "lite-server": "^2.3.0",
        "typescript": "^2.2.2"
    }

tsconfig.json changes:

angular 2 to angular 4

Upgraded tsconfig.json content

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

Clean your node_module directory after altering the package & tsconfig files.

Run the below command in the node root directory which will make your Angular 2 application up and run in Angular 4 framework.

npm install && npm update && npm start

Key points for Angular 4 development

  • Don’t use extends onInit event or with any life cycle event.
  • Don’t use DefaultIterableDiffer,KeyValueDiffers#factories or IterableDiffers#factories.
  • Don’t use deep import as it is not a part of public API.
  • Don’t use Renderer.invokeElementMethod as it is removed. (No replacement as of now).
  • Rename template tag to ng-template.
  • Replace OpaqueTokens with InjectionTokens.
  • Remove ChangeDetectorRef argument from DifferFactory.create(…).
  • Replace ngOutletContext with ngTemplateOutletContext.
  • Replace CollectionChangeRecord with IterableChangeRecord.
  • Import BrowserAnimationsModule if you are using animation in your application.
  • Replace RootRenderer with RendererFactoryV2.
  • By default, novalidate will add to the FormModule. To revoke the native behavior add ngNoForm / ngNativeValidate.

Finally, now you are good to go with Angular 4.

Setup Sass In Create-React-App Without Ejecting

If you are using Create-React-App module to manage your no configuration react application development environment, this guide is to setup Sass compiler into the environment without ejecting the setup.

Setup Sass In Create-React-App Without Ejecting

We know create-react-app comes with eject option, which will deploy all automatic confirmation to manual configuration, Even for a professional developers, it will be a headache while doing an upgrade in future. Currently, the create-react-app doesn’t come with Sass compiler but we can integrate it out of the box. This tutorial is to explain how to setup Sass compiler in the existing/new application without ejecting.

Node and NPM needs to be installed before continuing following steps.

Step 1:

Create react app using create-react-app by following syntax

npm install -g create-react-app
create-react-app
my-app cd my-app/
npm start

Step 2:

Install node-sass-chokidar from npm

npm install --save node-sass-chokidar

Step 3:

Open package.json and add the following into scripts configuration.

"scripts": {
“build-css”: “node-sass-chokidar src/ -o src/”,
“watch-css”: “npm run build-css && node-sass-chokidar src/ -o src/ –watch –recursive” }

To watch sass and compile use following command

npm run watch-css


Step 4:
Sometimes we miss to run the command while running the application, So let’s add this watch css to the application run command.

"scripts": {
“build-css”: “node-sass-chokidar src/ -o src/”,
“watch-css”: “npm run build-css && node-sass-chokidar src/ -o src/ –watch –recursive”,

 

“start”: “react-scripts start”,

 

“build”: “react-scripts build”,

 

“start-js”: “react-scripts start”,

 

“start”: “npm-run-all -p watch-css start-js”,

 

“build”: “npm run build-css && react-scripts build”, }

now we don’t need to run separate commands to compile css.
Now running

npm start

and

npm run build

The command builds Sass files too.

Simple Method to Localize your Angularjs Project

Localize your Angularjs Project is so simple, Angularjs has its own l10n & i18n scripts which are responsible for localizing the date, number and currency into your project but it has some restrictions with it. If you want to load specific locale library from angular js it can be done it by adding the corresponding locale via the script tag. But in case if you want to change the locale or language inside the application while it is running without reloading the page then here comes a simple solution.

localize angularjs app

Mission

The mission is to implement localization into the project without injecting any third party modules “angular-translate” into our application.

Mission Accomplished

Now am going to brief how I implemented localization manually

  1. Creating resource.json for the different language which holds all your translation as a json object.
  2. Get the JSON data using “$resource” and assign it to an object under “$rootScope”.
  3. Copy new locale object of corresponding to the language to $locale.

Creating  separate resource JSON

I created a separate folder which holding the localization object for the different object. The final level holds the name of the Locale Id, which is going to decide in what language our application renders.

This is how the folder Structure for resource.json created

-app
|_ l10n
|__en-us
|____resource.json
|__de-de
|____resource.json

This resource.json holds all the static value of my app. In all my HTML I use the key to rendering corresponding value.

whenever the user changes the language I get the unique language ID and make a $resource call and get the appropriate resource.json to render the values in selected language.

The same resource.json holds my locale object which is responsible for the date, number & currency formats.

Angular Js localization module on GitHub

Access the above mention URL and open the required language JS and copy the locale object from corresponding js to your resource.json

sample resource.json with Static & locale values for the German language.

{
 "indexPage": {
    "welcomeNote": "Willkommen bei icodefy",
    "followUs": "Folge uns"
    },
 "homeMenu": {
    "home": "Zuhause",
    "aboutUs": "Über uns"
    },
"locale": {
"DATETIME_FORMATS": {
"AMPMS": [
"vorm.",
"nachm."
],
"DAY": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"ERANAMES": [
"v. Chr.",
"n. Chr."
],
"ERAS": [
"v. Chr.",
"n. Chr."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"SHORTDAY": [
"So.",
"Mo.",
"Di.",
"Mi.",
"Do.",
"Fr.",
"Sa."
],
"SHORTMONTH": [
"Jan.",
"Feb.",
"M\u00e4rz",
"Apr.",
"Mai",
"Juni",
"Juli",
"Aug.",
"Sep.",
"Okt.",
"Nov.",
"Dez."
],
"STANDALONEMONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d. MMMM y",
"longDate": "d. MMMM y",
"medium": "dd.MM.y HH:mm:ss",
"mediumDate": "dd.MM.y",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
}, {
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}]
},
"id": "de-de",
"localeID": "de_DE"
}
}

Get resource.json Data using $resource and copy to $locale

Whenever the user changes the value in the language dropdown I call the appropriate file URL using $resource request and get the resource.json and reassign it back the $rootScope.l10n which hold all the static value of the application.

Here $rootScope.lang is the value bind from the language dropdown which is changed by user.

$resource('/app/l10n/' + $rootScope.lang + '/resources.json')
  .get(function (data) {
            $rootScope.l10n = data;
            // inject LocaleFactory in controller
            LocaleFactory.setLocale($rootScope.l10n.locale);
        });       

LocaleFactory is created for the component reusability. The angular.copy function can also call directly.

.factory('LocaleFactory', function ( $locale ){
 return {
  setLocale: function (currentLocaleObj) {
  angular.copy(currentLocaleObj, $locale);
 }
};

Drop your valuable comments and improvement suggestions in the comment section.