Angular2: Detect change in route in Angular2

Standard

In order to get information about landing page Url and previous page Url in Angular2, use below mentioned solutions:

Solution 1:

import { Router, NavigationStart, Event as NavigationEvent } from '@angular/router';

constructor(router:Router) {
  router.events.forEach((event: NavigationEvent) => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

Solution 2:

You can also filter by the given event:

import 'rxjs/add/operator/filter';

constructor(router:Router) {
  router.events
    .filter(event => event instanceof NavigationStart)
    .subscribe((event:Event) => {
      // You only receive NavigationStart events
    });
}

Solution 3:

import 'rxjs/add/operator/pairwise';
import {Router} from '@angular/router;

export class AppComponent {
    constructor(private router: Router) {
        this.router.events.pairwise().subscribe((e) => {
            console.log(e);
        }
    });
}

Angular2: Error – Can’t bind to ‘ngForOf’ since it isn’t a known property

Standard

While displaying data from web-api in html code, I used *ngFor, which is a repeater directive — a way to customize data display.

2016-10-28-16_40_42-speechimdb-microsoft-visual-studio

I came across below issue: 

EXCEPTION: Unhandled Promise rejection: Template parse errors:
Can’t bind to ‘ngForOf’ since it isn’t a known property of ‘li’.
Property binding ngForOf not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the “directives” section

 

2016-10-28-16_37_01-home-page-my-asp-net-application

Solution:

You should import the BrowserModule in your app module and import CommonModule in children modules. You should only import BrowserModule once. Other modules should be importing CommonModules instead.

Children Module(Dashboard):

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

import { DashboardComponent } from './dashboard.component';

@NgModule({
 imports: [
     FormsModule,
     CommonModule
   ],
 declarations: [
     DashboardComponent
   ]
})

export class DashboardMainModule {
}

Main Module:

import { NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { DashboardMainModule } from './dashboard/dashboard.module';
import { AppComponent } from './app.component';

@NgModule({
 imports: [
    BrowserModule,
    DashboardMainModule
  ],
 declarations: [
    AppComponent
  ],
 bootstrap: [
    AppComponent
  ]
})

export class AppModule {
}

Visual Studio: Keep IIS Express running site after stopping debugger in Visual Studio 2012-2013-2015

Standard

In order to keep IIS Express running after stopping debugger, Everyone knows the simple solution which is:

“in the Debug menu > Start without debugging (Ctr + F5)”

Apart from that, I am suggesting couple of other solutions below:

Solution 1:

add “Detach all” shortcut on the toolbar instead of the “stop” button.

Instead of hitting the (X) STOP button, you can use the Detach all menu item in the Debug menu. The major difference is that the stop button will terminate any process that is currently being debugged, while Detach All will disconnect the debugger from the processes, but will not terminate them.

The normal IIS worker process would also be terminated, but since it used to be running as a service, it will also automatically start up again and thus you could continue to use it without having to restart the process through |> Debug or |> Start without debugging.

enter image description here

Solution 2:

Similar to VS 2013, if you disable Edit and Continue IIS Express will continue to run when you stop your debug sessions.

Open the menu item Tools/Options, look for the Debugging/General option. Scroll down and uncheck “Enable Edit and Continue”

screenshot_3

Solution 3:

Right click your project > click Properties > select the ‘Web’ tab on the left > uncheck the ‘Enable Edit and Continue’ checkbox.

edit and continue option vs2013

 

 

Angular2: Lazy Loading in Angular2 Error: BrowserModule has already been loaded. If you need access to common directives

Standard

While implementing Lazy Loading in Angular 2, came across this error:

EXCEPTION: Uncaught (in promise): Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.

screenshot_5

Solution:

As error description is self explanatory, the module for which you want to implement lazy loading shouldn’t import BrowserModule as this is already been imported earlier (mainly in app.component). You should only import BrowserModule once. Other modules should be importing CommonModules instead.

See code below for understanding:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SearchMovieMainComponent } from './search-movies-main.component';

@NgModule({
    imports: [
        CommonModule
    ],
    declarations: [
        SearchMovieMainComponent
    ]
})
export class SearchMoviesMainModule {
}

 

Angular2: Lazy Loading in Angular2 Error: Cannot find ‘default’ in module

Standard

While implementing Lazy Loading in Angular 2, came across this error:

EXCEPTION: Uncaught (in promise): Error: Cannot find ‘default’ in ‘Scripts/app/search-movies/search-movies-main.module’

screenshot_5

Solution:

as stated in official documentation https://angular.io/docs/ts/latest/guide/router.html

If we look closer at the loadChildren string, we can see that it maps directly to our crisis-center.module file where we previously built out our Crisis Center feature area. After the path to the file we use a # to denote where our file path ends and to tell the Router the name of our CrisisCenter NgModule. If we look in our crisis-center.module file, we can see it matches name of our exported NgModule class.

Add the exported class name of your module to the loadChildren string after hash(#)

{
    path: '',
    loadChildren: 'app/search-movies/search-movies-main.module'
}

change to

{
    path: '',
    loadChildren: 'app/search-movies/search-movies-main.module#SearchMoviesMainModule'
}

 

 

Angular2: Import Lodash into Angular2 application using Typescript

Standard

Follow below steps to add lodash into your Angular2 app using Typescript 2.0.

Please note I am using Typescript 2.0 and Angular 2.0

Step 1:

Include lodash as the dependencies in package.json file by CMD

> npm install --save lodash

Step 2:

Include lodash typings as the dev dependencies in package.json file by CMD for Typescript otherwise you will get error in Visual Studio/Visual Code that “Cannot find module ‘lodash’

> npm install --save-dev @types/lodash

After above commands your package.json will be updated as below:

screenshot_1

Step 3:

As I am using systemJS to load module, so Update the systemjs.config.js file to map lodash. This file provides information to a module loader about where to find application modules, and registers all the necessary packages.

map: {
        'lodash': 'npm:lodash'
     },
        
packages: {
            lodash: {
                main: 'index.js',
                defaultExtension: 'js'
            }
          }

Step 4:

Import lodash in your angular component.

import * as _ from "lodash";

Please note that If you use import _ from “lodash”, you will receive following error that “Module ‘lodash’ has no default export”:

screenshot_3

Step 5:

Use lodash in your code as per need just like below as I am using _.isEqual(a,b) and IntelliSense is working fine:

screenshot_4

Update:

Lot of things have been changed since Angular2 RTM, I was having issues like “cannot find namespace ‘_’ and Cannot find name ‘many’ ”

Solution: Update @types/lodash in package.json to Typescript 2.0 compatible types in order to use lodash without any issue

"@types/lodash": "ts2.0"

Visit this link for complete solution:

Cannot find name ‘many’ and namespace ‘_’ issues with Lodash in Angular2 application using Typescript

 

Cheers. Happy Coding.