Friday, November 10, 2017

Angular Language Service - A handy extension for angular developers

Even though there have been plenty of tools/extension to check the typescript/javascript code, but there have not been any extension to validate the HTML code or related features to it. Angular Language Service was released to make the developers more productive and reduce the errors by offering better code completion. This service is available in the market place for installation for the Visual Studio as well as other code editors that support Type Script. Errors can be detected at the time of code creation . Hints are also provided for code completion. This effectively allows us to use the Intellisence for variables defined and used in the template. The navigation service is provided to link properties and their definition. This extension provides a rich editing experience for Angular templates, both inline and external templates including:

  • Completions lists
  • AOT Diagnostic messages
  • Quick info
  • Go to definition

The language service is developed by the Angular core team. At the time of writing, it is ready to use in VSCode, Sublime Text and WebStorm.

Language service uses the Angular compiler for parsing our application and producing diagnostics. It decorates the TypeScript language service in and uses its logic again. The coolest feature about the service is that it is not coupled to a specific Angular version and can be used in any text editor and IDE as soon as there’s an available plugin.

More about the language service can be found in the ng-conf talk by Chuck Jazdzewski (the creator of the language service) “Using the Angular Template Language Service”.

Start using in your angular projects and be more productive. Cheers!

Friday, September 8, 2017

Into the world of stackoverflow - Tips and tricks

It's been so long since i wanted to write a blog on stack overflow,  finally time has arrived after realizing its high time to write one. Recently me and one of my colleague had a small session on the same topic and i decided to share the experience in this post and this is a good opportunity to address some misconceptions about Stack Overflow.

let's dive into the world of stack overflow.

Programming became a lot easier these days when you could just type a question into Google and it would find that someone asked the same question in stack overflow. Stack overflow offers helping hand to all developers out there. When it was started in 2008 by
Jeff Atwood and Joel Spolsky one of the aim was to have a repository of great questions and answers. It revolutionized the way of quesitioning and answering should be. The main reason for success of stack overflow is accountability. It's managed by the community and community keeps the environment. For example, if you post some bad video on youtube it still spreads over the world and even if you want to remove it it takes number of days and you have to go through lot of process. In case of stackoverflow there is always a guarantee that good content is always delivered and maintained.
It has multiple features embedded. It has the various concepts which are similar to,
Wikipedia - Answers/questions are editable by anyone once you reach level of repuation
Digg/Reddit - It has the same ranking system in the form of reputation so that the best content rises to the top
Forum - Similar to any kind of forum, it has the feature to comment on someone's question or answer.
Blog - Blogs can be embeded as links inside the answers so that you could get more visitors to your blog.
There have been around 7 million active programmers ask and answer the queries related to programming on stack overflow. It is a better reflection of what you do professionally. For any programmer answering and asking questions on stack overflow is a great learning method.

Lets see why do you want to contribute to the community via stack overflow. As a programmer you have the responsibility to give something back to the community. You got to learn from everyone everyday which makes you a better programmer. How do you make you a better with the help of stack overflow
(i) You read awesome code by others
(ii) You get the feedback from other awesome developers on your code
(iii) Competition factor (reputation and ranking) which automatically drives you to learn.
Being an awesome programmer will automatically make people to have an eye on you.

How to start if you are new to stackoverflow?

Starting with stack overflow is once  again a bit of hard task which is similar to owning a startup where reputation that you earn is the investment. Initially it is very hard to find questions you can answer  and you can't ask clarification without comment rights. 


(i)Set up a good but short list of Interesting and Ignored tags. :
It is one simple tactic that you could follow to start answering questions, say if you are interested in answering angular questions, you can filter the questions with the tag angular and it keeps getting updated in the time line.

(ii)Try answering at a time of day or day of week when there are fewer users on Stack Overflow and presumably less competition for answering questions. 

According to the following graph, It appears that  heaviest users on stack overflow are from North America as seen here so the lightest times are when North Americans are sleeping. Try answering the questions at that time. 

 (iii) Earn your initial reputation by asking question:

 One simplest way to earn your initial reputation by asking question and accepting the answers which would give you a reputation of 2 and if the question is really good you will be earning a reputation of minimum 15. One common mistake the newbies tends to do is not accepting answers. Always make sure to mark the correct answers.

(iv)Rubber duck debugging - Asking question and answering yourself is one of the best way to start your initial account on stack overflow.

Lets see, How to ask good questions?

There is already FAQ section, but i would like to share my experiences on how to ask a good question.

It should be precise - The questions should not be too broad or too small. It should be very precise. A good question for example,

i tried x and here is my code it does not work and i cant figure out why, here is a piece of code you can reproduce the problem which makes a great question.
Proof-read before posting a question - Do a little bit of research on the question that you are going to post if it already exists in the site and be clear on it.

Include all the relevant tags: Always include the relevant tags with the questions which makes to get answers easily and to filter.

 Don't post a question and run away - One of the common mistakes i see with the new users is that there is no response if there is any further clarification, it is always better to wait for the first interaction which makes answers to come easily.  

 Format Question - Always format your question with the for matter so it is easy for others to get a clear idea.

Next, we will see on How to Write a better answer for the question?

Writing answers is the best way to earn your quick reputation on stack overflow. 

(i)Minimum viable answer - To earn your reputation fast, start with a minimum viable answer it should be working and properly formatted.

(ii) Iterate it : Always try to iterate the answer by adding step by step instruction , explain what does the code do. Also attach a working example code snippet with high level description of concepts. You can also use some of the following tools to attach the demo with the answer. Best way is to use the existing code editor to show the demo or proposed solution. I will be writing a detailed blog on the same. 
(iii) Give credits to the author: Whenever taking an answer from blog or an existing stack overflow answers, give credits to the author by adding the link. Always include the content inside the link rather than just adding the link, which would stay forever even if the link is removed later.

Lets see about earning reputation and badges 

Reputation is rough measure of how much community trusts you, communication skills, quality of your questions and answers. The more reputation you earn the more the privileges you get. 

Up votes and Down votes:

If you want to thank someone up vote, mark as answer. If you see good questions that really helps others up vote them. You can read more about reputaiton and how it works. Always try to upvote the best answers so that it goes to the top.

Always take down votes in a sportive manner, down votes are not for demotivating or stopping you from answering, it's a hint for you to make the answer/question better and don't take it personally.

You should not specicically try for getting the badges, because it comes with the reputation which you gain from your experience. Even though there are some badges which you can try intentionally.

Self learner - Answering your own question
Autobigographer - When you fill all your details in your profile. Here is an example.
Analytical - Visit all fields of site FAQ
Critic, Supporter , Editor - when you first down vote up vote and do your first edit
student or teacher - Simply answer and get 1 up vote
commentator - After you leave 10 comments
promoter and investor - when you offer some reputation to other users

Best practices to do: 

Don't be in a hurry

Onne suggestion is to start in the list at between 6 hours to a day old questions if you are looking for particular questions on specific technology using filters. Questions that are old, that shouldn't be answered, have likely already been downvoted. So that can help you filter what to answer until you get more experience.

Pick questions that will stretch you.
In general you will not get as much reputation on older unanswered questions, but you can get practice answering questions, and since there is little rush to answer, you can pick a question that will take more research, and you have the time to go figure it out.

Don't answer poor-quality questions.

In general Before answering a question, do a quick search on the title of the question, and then using other related search terms that might turn up an identical question. Too often, a question is asked which has already been answered before, sometimes many times before. Vote to close or flag such questions using the "duplicate" reason, rather than posting yet another answer.

Make sure the question is clear and unambiguous, concisely stated, and contains a useful code example (most questions really should have a full Minimal, Complete, and Verifiable code example). If you have enough reputation, edit the question to improve it so that it meets those standards. If not down vote it.

It's always helpful to post a comment under the question to encourage the question's author to improve their question, explaining precisely how they can do so. Sometimes, this can be all it takes to help a question poster get their question on the right track.If this doesn't help, then you can flag posts that need to be closed, an ability you unlock at 15 rep. This is a great way for low rep users to help get questions closed. For example, if you find a duplicate, even if you can't vote to close you can still flag the question. This will leave a comment linking to the other post and will put the question in the Close Vote review queue for others to see.If you don't have enough reputation to post a comment, focus on other activities that will garner you the necessary reputation points (for example, answering other, high quality questions or editing posts that could use some help).

Things To Avoid

We have seen how to do things in the right way, In eager to gain more reputation lets see what are the things that you should not do. Here are a few things that could quickly get you into hot water, but are common mistakes:

Do not undo useful edits.
You would be surprised how many users get angry when their posts are edited! If you don't agree with an edit, you can undo it.However, if someone edits your post to completely change the wording, change your coding style, or otherwise change what your answer says, you are more than welcome to undo that edit.

Do not post a comment in the answer box.
This may seem self-explanatory, but a lot of people do this. Writing any form of "I don't have the rep to comment, so I'm posting this as an answer" does not excuse this act.
Long story short, just don't do it. If you don't have the rep to do something, then don't try to workaround it please. Your post will be deleted at best, and you'll have angry users to deal with at worst.

Don't post just a link to answer a question.
Stack Overflow is meant to be a high-quality repository of problems and their solutions. To accomplish this, we like to have posts be as self-contained as possible.If you link to a tool/plugin/library that will solve a user's problems, great! But please, explain why or how that tool helps. Even better, show how, if possible, to use the tool to solve the problem. A brief code snippet showing how to use a library, for example, or the function the user needs to call and how to incorporate it takes a low-quality or average answer and helps make it a good answer.If you're linking instead to documentation or a blog or such to help explain something, quote the relevant part of the page and explain in your own words how it answers the question. If the relevant part is the entire linked page, summarize it as best you can and explain how this helps.

Don't plagiarize.
To meet the last point, you might decide to just copy and paste large parts of pages to your answer. Don't do this! If the section you're copying is large, try to summarize. Always provide a source to the page and give proper attribution. Put anything you quote this way in a blockquote. Hit the quote key on the toolbar, or insert a > before each line of the quote. If you are quoting another answer on Stack Overflow, check if the questions might be a duplicate of each other. If yes, flag one of them as duplicate of the better one.

Don't post images of code or text.
This might also seem like a no-brainer, but a lot of people do this.Posting images of your code, error message, console output, etc. make it harder for your post to be found through searches, or for readers to paste what you have presented into their editor window. It also makes things much more difficult for users with screen readers.If you can't copy and paste, it's far more preferable to hand-type anything you can. If an error is long, try to post the most relevant part of the error and not the whole thing.

Don't try to be the fastest gun in the west
A well thought-out answer that takes longer to write is better than "Try this" followed by a code dump. Posting an incomplete answer so it gets seen first can lead to down votes from users who don't find it useful, even if you intend to improve it with later edits.

What is #SOAReadyToHelp?

Most of the high reputation profiles in Stack overflow will have the above tagline.It was a contest from 2015 to celebrate the 10 million questions in Stack Overflow.Users were asked to share the experience about Stack Overflow in Twitter with the #SOreadytohelphashtag. So if you are new to stack overflow add it in your profile.

Finally here is the video on the session

I will be writing a separate blog on advantages of being an active user on stack overflow and its benefits. Well those are some of the tricks that you can take from this blog to gain more reputation on stack overflow and more importantly you got to learn and share your experience and contribute to the community. Happy contributing!

Wednesday, August 9, 2017

Angular 2  —  Exception Handling Mechanism

One of the main issue which i came across with angular2  was error handling.  When you are developing an application, you are in full control, and you will be able to see the errors and handle them accordingly.
But as you soon deploy it in the production,  you can’t see what your user is seeing and experiencing and you not capable of knowing about errors unless you find a way to be notified about the exceptions.
This solution i have implemented recently and it worked pretty well. Angular 2 has his own way to catch and handle errors. The default implementation of ErrorHandler prints errors messages to the console. You can intercept the default error handling and write a custom exception handler that replaces this default as appropriate for your app.
If you have a production server and you want to send the errors to the server, Let’s see how we can do it.

you need to create your own ErrorHandler class that implements the default ErrorHandler. The only method that required is the handleError method that takes the error as an argument.

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  

The next step you can go is to change your injector to use your implementation instead of the default. So code will be something like this,

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  

That’s all folks. If you don’t want to ignore the Angular default handler, you can extend the ErrorHandler class and also call the default handler like this:

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  

That's it guys!. You can apply this method on your application and make it error free on production. 
You can check the sample on plunker and play with it!

Monday, August 7, 2017

Google search tip for angular

This tip is for Angular enthusiasts, whenever you search something on google for angular, it will end up showing the results with angularjs(1.x) aswell. To avoid this, you could simply do the following

add “ -AngularJS “ to your search query

For example,

Will return only the results which matches angular. This will seriously improve the productivity and help rapid development. Spread this tip across your friends.

Monday, July 31, 2017

Running Python Inside SQL Server

One of the valuable addition to data analytics by Microsoft was adding python into SQL server.Now SQL Server will support the two primary languages of Data Science within SQL Server R and Python. I am a fan of Python and  Python is near the top of the most popular programming language charts, many people are interested in learning more about it.  As many professionals are unfamiliar with Python, i wanted to this post about the same.

Installing Python in SQL Server

If you have already used R with SQL server then the process for using Python in SQL Server is very similar to it.  Microsoft renamed R Services to Machine Learning Services, and now allows both R and Python to be installed, as shown in the screen.  Microsoft’s version of Python uses Anaconda, which is an open source analytics platform created by Continuum. This is where Python differs from other open source languages, as Continuum is providing the version of Python as it contains data science components which are not included in the standard distribution of Python. Continuum also sells an enterprise version of Anaconda, with of course more features than come with the free version. Also it is mandatory and  important to remember the python environment as you will need select the same distribution when running Python code outside of SQL Server.

Configuration Changes for Python

The last thing needed to run Python is to configure and restart the SQL Server Services. In a new query type the following command

 sp_configure 'external scripts enabled', 1  

After restarting the SQL Server Service, SQL Server will now run Python code. Since Python is easy to learn for even a novice developer. Code is easy to read and you can do a lot of things just by looking at it. Lets dig into python with sql server and do wonders with data analytics.

Saturday, July 15, 2017

Angular 4.3 Now released

Angular version 4.3 has been released. This is a very minor release.

What’s new?
  • It has HttpClient, a smaller, easier to use, and more powerful library for making HTTP Requests. Learn more about it from the docs
  • New router life cycle events for Guards and Resolvers. Four new events: GuardsCheckStartGuardsCheckEndResolveStartResolveEnd join the existing set of life cycle event such as NavigationStart
  • Conditionally disable animations via a new attribute, [@.disabled]
  • Support for the emulated /deep/ CSS Selector (the Shadow-Piercing descendant combinator aka >>>) has been deprecated to match browser implementations and Chrome’s intent to remove. ::ng-deep has been added to provide a temporary workaround for developers currently using this feature. 
Wondering what have changed ? For the complete list of features and bugfixes check the changelog.

Sunday, June 11, 2017

Build a select dropdown with *ngFor in Angular 2

One of the most repeated questions with angular2 i have come across Stack overflow is "how to generate a select dropdown with an array or object". Hence, i decided to write a sample post with sample code to ease the search.

I will be posting two samples with one simple array and other with object.

Assume you want to generate a dropdown select by having an array with years.

  years = ['2016','2015','2014'];  

The app.component.ts code will look like,

 import {Component} from '@angular/core';  
 import {Http} from '@angular/http'  
 import {bootstrap} from '@angular/platform-browser-dynamic';  
 import { Component } from './Component';  
  selector: 'material-app',  
  templateUrl: 'app.component.html'  
 export class AppComponent {  
  years = ['2016','2015','2014'];  
  selectedyear = '2015' ;  
  onChange(year) {  

In the above cocde selectedyear indicates the default value of the dropdown whenever the app is loaded.  onChange is the event gets fired whenever a option is changed, you can capture the selected value with the event.

And the template  app.component.html will look as follows,

*ngFor is being used to repeat the items as options. It's simple as above.


Next we will see how to bind a object using *ngFor . Assume  if you have a object and want to bind the keys as drop down values,

 currencyList = {  
 "USD": {  
 "symbol": "$",  
 "name": "US Dollar",  
 "symbol_native": "$",  
 "decimal_digits": 2,  
 "rounding": 0,  
 "code": "USD",  
 "name_plural": "US dollars"  
 "CAD": {  
 "symbol": "CA$",  
 "name": "Canadian Dollar",  
 "symbol_native": "$",  
 "decimal_digits": 2,  
 "rounding": 0,  
 "code": "CAD",  
 "name_plural": "Canadian dollars"  

to get the keys of object you can use  Object.keys(this.currencyList); and the rest is same as above sample.


Sunday, June 4, 2017

ESLint with Visual Studio Code (vscode)

Poor code quality application can lead to many serious problems when the size of code grows. Linting is the process of checking the source code for Programmatic as well as Stylistic errors. This is most helpful in identifying some common and uncommon mistakes that are made during coding. To do this process many linters are out there like eslint, jshint, jslint etc.  

All the above helps us to be consistent in semicolons, quotes & code formatting etc. In this blog post i will be showing you how you can setup ESLint with visual studio code which is my favorite code editor.

Install ESLint global

Install it globally by using NPM by this command:

 npm install -g eslint  

Download ESLint extension 

Install the ESLint by downloading the extension, as shown below,

After downloading we need to initialize the ESLint.

Initialize ESLint in project

Next is to initialize ESLint by using Ctrl + ` to open the terminal in Visual Studio Code

That's all folks, now your project is setup with ESLint, from now on it will be very easy to catch lint errors and fix them even if you had missed it. Let's see ESLint in action.

And if you want to explore more on ESLint you can explore it on the website

Saturday, June 3, 2017

How to copy a Database from a MongoDB instance to another?

While recently i was working in an application i had to copy the database from a mongoDB  hosted in an mlab instance to my local. I will share an easy step in MongoDB Shell which support to copy database from remote instance to current one with a single command.

DEMO with steps :

I made  two instances of MongoDB from following commands.
 //Instance 1  
 mongod --port 9998 --dbpath /data/db1  
 //Instance 2  
 mongod --port 9999 --dbpath /data/db2  

In instance 1 there is a database called "dsampledb1".
and i started the instance with the following command,

 mongo localhost:9998  

I create a database with one collection with the following command,
 use dsampledb1{id:1, name:"sample name"})  

Then I log in to next MongoDB instance using MongoDB Shell.
 mongo localhost:9999  

Now to copy the database from the instance 1 to instance 2 , we can simply use the following command,

Syntax is as follows,
 db.copyDatabase(sourcedb, destinationdb, fromhost, username, password)  

A first-timer’s experience of Microsoft’s MVP Community Connection (MCC)

It was my first ever experience to participate in Microsoft's event outside Sri Lanka. My experience as a “first-timer” attending the South East Asia's MVP community connection, along with few other MVPs from my country. MVP Community Connection is a day to connect, learn, inspire and celebrate the local MVP community and MS employees.

It was an exclusive event especially organized for Asia pacific MVPs. The intention is to have all MVPs from different region join there and have a great time with others. There were some interesting sessions and networking between each other. 

From the moment I got off the plane at the Soekarno–Hatta International Airport Airport, I was very excited about the event. I was the first to arrive AYANA Midplaza JAKARTA 2 hours prior to the event. From the registration, greeted by Microsoft mvp tshirt and  I was escorted to pick up my personal registration badge and Wahoo!. 

First day started with lunch at the Hotel. Everyone had a very good time introducing ourselves in 1 minute with other MVPs.  There were totally around 50 MVPs from various countries in south east Asia and we were snuffled and divided into 7 teams for various activities and sessions. It was really awesome to meet with other MVPs and get some inputs, their works and other things related to personal and professional life. Later with a key note from Soyoung Lee, Community Program Manager on "MVPs for the year 2017 and latest updates". Then we had  hack a plan session on  various topics such as "Emerging Technologies", "Developer Field Presentation" etc andone of the best moment was the group photo .

 Later in the evening we were out for dinner where we had Indonesian varieties of food and MVPs were involved in presenting their culture in various ways.  Finally everyone had a great time and fun on the first day.  Second day, it started with a fantastic breakfast and a team activity , later there were  very productive intense discussions to improve MVP engagement within the Partner network. The day ended with a award ceremony where everyone who attended the session was given away with a cool gift. It was a tremendous experience I had at MVP community connect event at Jakarta,Indonesia. There were lots of things that i could learn from various MVPs. Also it created a very good channel with all other MVPs.  

Saturday, March 18, 2017

Microsoft - A Big Thank You

1/03/2017 was a huge day in my career as I was awarded my first (and hopefully not the last) Microsoft Most Valuable Professional award under the category Visual Studio and Development Technologies. It was such a  Indescribable honor, and i have to give a shout out here to the Microsoft community for their support. There have been so many great mentors/supporters in my career over the past 6  years.Thank you  MVP Community Program Manager, my friends, colleagues, my company,followers and supporters for helping me to get my Microsoft  MVP Award for this year.

I hope this marks only the beginning of this new phase of my professional life and I feel so very lucky to be among the 6 technology leaders under the same category in Sri Lanka. Microsoft has always been a great supporter of the community, and a real partner in our ongoing efforts. I will make sure to work extra hard to give back (even more) to the community and I will be more glad to do it every day! Thank you Microsoft!Thank you to the MVPs who welcomed me and others have helped me throughout the years!

Sunday, March 12, 2017

Visual Studio 2017 has landed!

It has been an amazing journey for Microsoft Visual studio , Recently marking 20 years of software development tool in the industry. Tech giant Microsoft has introduced the discharge of Visual Studio 2017. Users can obtain visual Studio 2017 by visiting

Every Visual studio fan would have been excited about the release of Visual Studio 2017. Let's see what Visual Studio 2017 offers us ahead of the previous versions.

In one sentence, The builders can use Visible Studio 2017 to create purposes for Android, iOS, Home windows, internet, and cloud. “Code fast, debug and diagnose with ease, test often, and release with confidence".

Productiveness and efficiency , Developers life made easy:

Working with your team with one repository has never been easier. Now we can use the new 'Open Any Folder' feature to immediately open and work with virtually any code file without a formal project or solution around it.

Codebase Navigation:
Visual Studio 2017 refreshes the navigation experience with the following features,

Go To Implementation (Ctrl+F12) – navigate from any base type or member to its various implementations.

Go To All (Ctrl+T or Ctrl+,) – navigate directly to any file/type/member/symbol declaration. You can use the icons along the top of the feature to filter your result list or use the query syntax (e.g., “f searchTerm” for files, “t searchTerm” for types, etc.).

Find All References (Shift+F12) – now with syntax colorization, Find All Reference results can be custom grouped by a combination of project, definition, and path. You can also “lock” results so that you can continue to find other references without losing your original results.

Indent Guides ­– dotted, gray vertical lines act as landmarks in code to provide context within your frame of view. You may recognize these from the popular Productivity Power Tools.

With Visual studio 2017 there has been fre tweaks and additions to make the common
tasks more productively

IntelliSense – User can filter necessary completion list by category by clicking on the icons in the tray or by hovering over them to learn the keyboard shortcut.

Refactorings – use ‘Ctrl+.’ to access all the refactorings and quick actions we’ve added in VS.

Add using/Imports for types in reference assemblies/NuGet packages

Code Suggestions – code suggestions lee the user hint best practicess.

Mobile Support:
Mobile developers favourties both Xamarin and the amazing Visual Studio Tools for Apache Cordova are included in this 2017 release.  Xamarin integration in Visual Studio 2017 is a huge plus.

Testing and Debugging:

Visual Studio 2017 gives the developers debugging experience to identify the source of an issue faster with the following things,

The new Exception Helper

Run To Click

XAML Edit and Continue

Reattach To Process

Open for everyone:

Last but not the least, there is a FREE community version that everyone can try. Also
if you get  60 days of Xamarin University free if you download before 14 March 2017.

Here's a quick rundown of all the features that have arrived on the Visual Studio 2017:

Better startup and load time
Modified navigation with new features
Visual C++
Extended support for C# 7.0 and Visual Basic
Support for F# 4.1 language
Live Unit Testing
Introduction of Git features
Enhanced Visual Studio Feedback Workflow
Inclusion of .NET Core and ASP.NET Core libraries
Xamarin 4.3 support
NuGet support
Azure SDK for .NET
Office Developer Tools for Visual Studio
Developer Command Prompt
Installation Nickname, and other IDE improvements

So, what you are waiting for? Start to download Visual Studio 2017 and check out what's new? You will feel glad  as how i am. Cheers!

Saturday, February 11, 2017

Use Moment.js with angular2 application

Recently i was developing an application in angular2 where i had to use a calendar which shows the results for this month, this week and this weekend. I was finding a solution in pure javascript but it was time consuming. I decided to go on with moment.js , this is how i have embedded moment with angular2 application.

Step 1 : npm install moment --save

Step 2 : In your systemjs.config.js file's map array add:

'moment': 'node_modules/moment'

to packages array add:

'moment': { defaultExtension: 'js' }

Step 3 : In your component.ts use: import * as moment from 'moment/moment';

and that's it. Now you should be able to use moment with your application.

public setDate(term: string) {
    var status: string;
    status = term;
    switch (status) {
      case "today":
        this.fromDate = moment().toDate();
      case "tomorrow":
        this.fromDate =  moment(new Date()).add(1,'days').toDate();
      case "weekend":
        this.fromDate = moment().startOf('week').add('days', 6).toDate();;
        this.toDate = moment().startOf('week').add('days', 7).toDate();
      case "thisweek":
        this.fromDate = moment().startOf('week').toDate();;
        this.toDate = moment().startOf('week').add('days', 7).toDate();
      case "nextweek":
        this.fromDate = moment().startOf('week').add('days', 7).toDate();
        this.toDate = moment().startOf('week').add('days', 14).toDate();
      case "thismonth":
        var date = new Date(), y = date.getFullYear(), m = date.getMonth();
        var firstDay = new Date(y, m, 1);
        var lastDay = new Date(y, m + 1, 0);
        this.fromDate = moment(firstDay).toDate();
        this.toDate = moment(lastDay).toDate();