ASP.NET MVC 5 – Using Angular 2 with TypeScript in Visual Studio

ASP.NET MVC 5 is widely used web development framework, it’s stable, matured and most importantly its is used in production on large scale. Many folks had requested me to write how to wire up Angular 2 in MVC 5.

  • Update 31/3/17 – Github repo updated with Angular 4, TypeScript 2.1. Angular 4 is backward compatible with Angular 2 with much reduced bundle sizes.
  • Update 26/9 – Github repo updated with Angular 2 Final release version. Install TypeScript 2.0 RC

These steps can be used for new or existing MVC 5 application.

In this post I will summarize the steps needed to getting started with Angular 2 in MVC 5.

ASP.NET MVC 5 is full .NET framework web development framework, it’s different from ASP.NET Core 1.0

What we will learn?

  1. Adding package.json to MVC 5
  2. Configure to transpile TypeScript files
  3. Using gulpfile.js to move files.
  4. Add TypeScript files for bootstrapping
  5. Include systemjs.config.js to load Angular 2 modules
  6. Change HTML to load and render Angular

Step 1: Adding package.json to ASP.NET MVC 5

Assuming that you already have existing or creating new ASP.NET MVC 5. Lets add NPM configuration file known as package.json. It contains Angular 4 (works for Angular 2) & related package name to installed using NPM (Node). This is similar to package.config of NuGet.

Latest NodeJS & NPM needs to be installed.

package.json contains Angular 2 (using version 4) along with, system.js, RxJs and also some dev dependencies.

Open Command Prompt & navigate to package.json location, then run npm install this will install packages related to Angular 2 (using version 4) under node_modules folder in your folder structure.

They won’t be showing in project solution explorer, don’t worry they need not show.

Step 2: Configure to transpile TypeScript files

TypeScript(TS) would be new for most of developers, maybe these will give get started on TypeScript

In short – It’s superset of JavaScript, means everything you know about JS will be in use.

All TS files need to be transpiled or compiled to JS files so that we can run them on browser. To accomplish this we need to add “TypeScript Configuration File” called as tsconfig.json

Create a folder called “tsScripts” which contains all TS files and also configuration file. Create above tsconfig.json in this folder.

It’s fairly simple config “All TS files present in tsScripts folder will be transpiled using commonjs module to outDir (Output Directory) by keeping comments, sourceMap intact”

One of the important step is to create typings.json file, this file will create typings to ensure that TypeScript understands all Angular 2 (using version 4) modules in respect to ES5 standard.

Create JSON file with name “typings.json” & add below code then run command typings install from CMD

Step 3: Using gulpfile.js to move files

From Step 1 you got to know that all Angular 2, other packages are downloaded into node_modules in your solution folder. Now we need to move required files only like JS, sourcemaps (debugging on chrome) into our MVC 5 apps Scripts folder.

Step 2 also requires to move TS files to JavaScript file, so we use create GULP tasks which does this transpile. Also it contains CSS files movement also (which is not relevant at this point)

Create gulpfile.js in your project and copy this code

Step 4: Add TypeScript files for bootstrapping

As we are using Angular 2 with TypeScript, we need to add TS file to bootstrap the Angular app into MVC 5 app. So let’s create boot.ts file in “TsScripts” folder and copy this code.

We using ngModule to browser specifics, AppComponent.

AppComponent is starter component which we have to create it now (app.ts). Add this code below

This is template based app component which displays list.

Now create tsScripts/main.ts, this entry point where Angular 2 loads the components.

Step 5: Include systemjs.config.js to load modules

This is most important part of Angular 2 (using version 4) which loads it into the browser. There are different ways to load it but am using SystemJS here.

In the existing “Scripts” folder, create “systemjs.config.js” and copy below code

Step 6: Change csHTML to load and render Angular 2

To load Angular 2 in ASP.NET MVC 5, we need to include the script references in _Layout file and index.cshtml page.

In the Views/Home/index.cshtml you need to add “my-app” component we defined in app.TS file. This is starting point of Angular 2 application to render into browser.

Now that we are almost done, we need to run GULP tasks so that Angular 2 files, TS files are moved to appropriate folder. Open Task Runner Explorer in Visual Studio 2015 and run default task shown.

Its better to do show ALL Files in solution Explorer to see “libs“, “typings“, “app.js, boot.js, *.map” files. Includes these files and run the application to load Angular 2 in ASP.NET MVC 5.

ASP.NET MVC 5 Angular 2

Running Angular 2 in ASP.NET MVC 5

Entire source code is on my Github repo, clone or fork or download it and follow instructions to run it.

Let me know in comments if you face any issues running applications.

 

Leave a Reply

  1. tsc : error TS2688: Build:Cannot find type definition file for ‘node’.

    Getting this error. Tried a lot but all in vain

  2. Hi Mithun,

    It was nice article. I have followed the same steps and trying to setup angular 2 in our existing application. I am getting below error and not able to find what is causing this issue.Could you please help me on this.
    I have all js files after running gulp under scripts folder. In the system.config I have given reference as Scripts folder.
    I would really appreciate if you could help me to resolve this.

    16 Error: (SystemJS) XHR error (404 Not Found) loading http://localhost/MtStorage/smartcontent/Scripts/app.module
    Error: XHR error (404 Not Found) loading http://localhost/MtStorage/smartcontent/Scripts/app.module
    at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost/MtStorage/smartcontent/workspace/shared/libraries/angular2Libs/zone.js/dist/zone.js:1199:29) []
    at Zone.runTask (http://localhost/MtStorage/smartcontent/workspace/shared/libraries/angular2Libs/zone.js/dist/zone.js:165:47) [ => ]
    at XMLHttpRequest.ZoneTask.invoke (http://localhost/MtStorage/smartcontent/workspace/shared/libraries/angular2Libs/zone.js/dist/zone.js:460:38) []
    Error loading http://localhost/MtStorage/smartcontent/Scripts/app.module as “./app.module” from http://localhost/MtStorage/smartcontent/Scripts/main.js
    at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost/MtStorage/smartcontent/workspace/shared/libraries/angular2Libs/zone.js/dist/zone.js:1199:29) []
    at Zone.runTask (http://localhost/MtStorage/smartcontent/workspace/shared/libraries/angular2Libs/zone.js/dist/zone.js:165:47) [ => ]
    at XMLHttpRequest.ZoneTask.invoke (http://localhost/MtStorage/smartcontent/workspace/shared/libraries/angular2Libs/zone.js/dist/zone.js:460:38) []
    Error loading http://localhost/MtStorage/smartcontent/Scripts/app.module as “./app.module” from http://localhost/MtStorage/smartcontent/Scripts/main.js

  3. I have a question. I’m building an app in an MVC area in Visual Studio 2015. The app I built externally for now using Angular Cli. Now I’m trying to figure out how to embed this app into the MVC web project. can I follow these instruction and be fine or will I need to include these files in the web project and the Area?

    • Interesting question !! I would use CLI commands to create angular build (HTML file, bundles), then take that build & copy to MVC5 proj. Then in appropriate CSHTML add the bootstrapping Angular component Loading…. I am not sure how it works out, but give a try. Angular app will be mini SPA in MVC 5 project.

      • Thank you, that is how I have been handling this project so far. The only thing that I’m concerned with is the long term maintenance of the app. It will now be necessary to (ng build -prod -aot) in a separate project and then push the project and “dist” file every time a change is made.

  4. Great tutorial. I’m doing a proof of concept very similar to this tutorial except the part of copying the files from node_modules to scripts folder using gulpfile…
    Is it really necessary to move the js files from node_module to scripts folder? what is the big advantage since we are encapsulating the load of the files on systemjs.config.js?

  5. 1) In Visual Studio 2015 Options-Project and Solutions- External Web Tools

    Move the priority of the $(PATH) option upwards so it can find latest Gulp tool

    In my settings

    .\node_modules\.bin

    $(PATH)
    $(…

    (deals with a Gulp error findings tasks)

    2) Install Typescript for Visual Studio 2015

    Make sure Visual Studio is closed

    npm install

    npm install –save-dev @types/node

    (deals with deprecated node message)

    edit package.json

    Under devDependencies

    Downgrade to

    “@types/node”: “7.0.7”,

    (deals with a TypeScript exception iterator warning)

    3) Clean and Rebuild Solution

    4) Open Task Explorer (right mouse click) on Gulp.js

    Run watch task which scans for changes

    Should see a working solution

    Thanks for everyones contribution

  6. HI ,
    you have use MVC with Angular2
    but there is any issue

    how can i enable Angular2 Routing in this Project

    example
    I have Create Route in Anguar2 form
    1) /gallary
    2) /professional

    if i hit the Url From browser ,,, it go and check MVC Route .. and its says that “HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

    because you choose mvc so it go to that page and find contoller and method

    so can you help me out

  7. Followed your tutorial latest using angular 4 in my mvc5 app, using vs 2017.
    Getting errors before i can run gulp file,
    Error Build:Cannot find name ‘Set’. … cannot find name ‘Promise’…. map… etc etc

      • I have the same error “error TS2688: Cannot find type definition file for ‘node’. While installing typings it throws Warning “typings WARN deprecated 9/14/2016: “registry:dt/core-js#0.0.0+20160725163759″ is deprecated (updated, replaced or removed)” although it installs them at the end(I assume). I tried to search for the fix and it says to remove the part from the end that says”#0.0.0+20160725163759″ etc.. but even then no use. I am running node version 6.9.5 and npm version 3.10.10.

        I cloned the repository but same error.

    • Facing Same Error

      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/application_ref.d.ts(132,110): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/application_ref.d.ts(162,67): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/application_ref.d.ts(164,101): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.d.ts(24,16): error TS2304: Cannot find name ‘Map’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.d.ts(32,16): error TS2304: Cannot find name ‘Map’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/change_detection/differs/iterable_differs.d.ts(15,48): error TS2304: Cannot find name ‘Iterable’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/change_detection/differs/keyvalue_differs.d.ts(23,18): error TS2304: Cannot find name ‘Map’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/di/reflective_provider.d.ts(87,123): error TS2304: Cannot find name ‘Map’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/di/reflective_provider.d.ts(87,165): error TS2304: Cannot find name ‘Map’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/linker/compiler.d.ts(43,49): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/linker/compiler.d.ts(51,65): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/linker/ng_module_factory_loader.d.ts(14,34): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/linker/system_js_ng_module_factory_loader.d.ts(28,25): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/core/src/util/lang.d.ts(12,53): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/platform-browser-dynamic/src/resource_loader/resource_loader_impl.d.ts(10,23): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(79,33): error TS2304: Cannot find name ‘Map’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/platform-browser/src/dom/dom_adapter.d.ts(97,42): error TS2304: Cannot find name ‘Map’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/platform-browser/src/dom/shared_styles_host.d.ts(11,30): error TS2304: Cannot find name ‘Set’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/@angular/platform-browser/src/dom/shared_styles_host.d.ts(22,30): error TS2304: Cannot find name ‘Set’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/rxjs/Observable.d.ts(68,60): error TS2304: Cannot find name ‘Promise’.
      D:/Vagaro/branches/PublicRedesign_04_April_2017/Vagaro.Public/node_modules/rxjs/Observable.d.ts(68,70): error TS2304: Cannot find name ‘Promise’.

  8. Thanks for the nice tutorial! I followed the steps and everything works well. I have one question about copying libraries files to “libs” directory. What’s the purpose of this copying? Why can’t we just reference js files from node_modules folder? When we copy libraries to “libs” folder, they are duplicated. Or am I missing something? I would appreciate your reply a lot

  9. Please when I attempt to add more modules using the node js, upon compilation there multiple error coming from the modules themselves

  10. Hi Mithun,

    Its a vey good article with MVC 5. But when i use templateUrl property of component then it show me error like 404 page not found. I googled it lot and found that we have to add one more property like moduleId: module.Id in component. Then it says “could not find module”. Could you plz help me in this. Thanks in advance.

  11. Thanks a lot! Excellent article

    I faced issue in gulpfile.js file but I solved it

    gulp.task(“scriptsNStyles”, () => { –This code throwing error

    I replace same wtih gulp.task(“scriptsNStyles”, function () {

    and error solved

  12. Great tutorial and well documented git. However when trying to integrate this with my app I get an error that reads ‘Build cannot find module @angular core’. Researching the issue I think its a problem with the node_modules folder

    Any help on how to solve this would be great.

    Thanks

  13. I created new MVC 5 project. Followed the steps. But it is not working, tag is not filled. It stays “Loading”.
    I am using VS2015 Update 3

    I have updated some stuff, but that is not helping :
    – Updated typings to 2.1.0(when I installed typings there was message, that I should update and VS itself asked for that).
    – Updated core-js, jasmine and node, because I got message that given versions are old. Updated through console with command
    typings install dt~core-js –global –save
    typings install dt~jasmine –global –save
    typings install dt~node –global –save

    My current versions

    “core-js”: “registry:dt/core-js#0.9.7+20161130133742”,
    “jasmine”: “registry:dt/jasmine#2.5.0+20170207112528”,
    “node”: “registry:dt/node#7.0.0+20170204020307

    But that does not resolve issue. is still not updated

  14. thank you for this nice tutorial
    i had error at step 4 .. when i created file boot.ts i had error in
    ///
    because the path not found, so every thing depends on this is mistake

  15. Everything is working fine but i have a problem like if i change the name of the skills it doesn’t reflect even after reloading the page. So i have to close and open the Visual Studio and run the application again every time i change.Is there any other way so that i can see the changes after reloading the page?

  16. Pingback: Useful Angular 2 References – Kec Rocks!

  17. How do i install typings install from CMD. I cant figure it out. and whenever i rclick on gulpfile.js and open task runner, it shows failed to load. why this?

  18. We have an existing ASP.net MVC5 Web Application. We are about to embark on a new feature for the application that we believe would be condusive to an SPA style app as it is quite chatty. We want to use AngularJS 2.0. I have found many articles about how to set up Angular with an existing MVC app but still now sure how it will all work and look. i.e. What would the architecture look like? Do we retain the existing MVC navigation side bar or does the shell need to be rewritten? If initially only new modules would be SPAs i.e. written in Angular how would they work with the existing site? Or should they be separate sites? And if so how do we authenticate from one site to another? How should we migrate the controllers to API controllers?

  19. hello I follow your tutorial but I get several errors (150)
    The one of them is:
    Error TS2403 Subsequent variable declarations must have the same type. Variable ‘main’ must be of type ‘any’, but here has type ‘NodeModule’. TypeScript Virtual Projects C:\MyprojectName\node_modules\@types\node\index.d.ts 70 Active

    • Hello again, I manage to correct this issue, but now I get another one:
      Severity Code Description Project File Line Suppression State
      Error Build:Cannot find name ‘Set’. UploadFiles C:\MyProjectName\node_modules\@angular\common\src\directives\ng_class.d.ts 46

      Any idea?
      thank you

        • Hello I read the the steps on github but I dont need to create a new app because I have alreday one and I dont want to create all the code from the begging. Sorry because I didn’t paste the error correct. Actually is “Duplicate identifier Property Key” and another one among other is
          “All declarations of ‘name’ must have identical modifiers”. Thank you.

  20. Hi Mithun,

    I followed all the steps as mentioned in your code.

    I am getting below 2 compile time errors:
    1. Build:File ‘MyProjectpath/node_modules/gulp-typescript/lib/main.ts’ not found.
    2. Build:File ‘MyProjectpath/node_modules/gulp-typescript/typings/tsd.d.ts’ not found.

    Any help to resolve this error would be of great help.

    Also, I have below quries:
    1. As mentioned in gulpfile.js, I do not have libs folder – .pipe(gulp.dest(“./libs”));. Does this folder gets created on successful build?
    2. In tsconfig.json the attribute “module”: “commonjs”, I dont see the commonjs folder either.

    Kindly reply.
    Many Thanks,
    Krupa

    • There are few steps which you missed from article or github repo steps. You need to install typings to resolve first 2 errors.

      libs folder gets created when you run gulp task from Task Runner Explorer in Visual Studio. When using TypeScript, the transpiling (compiling) to JavaScript done using tsconfig.json and module resolution technique used is commonjs. Note it’s not a folder.

      • Thanks for the prompt reply.

        The first 2 errors are not coming now. Build is successful. But on running the gulpfile.js i am getting below error.
        Failed to run “myProjectpath\Gulpfile.js”…
        cmd.exe /c gulp –tasks-simple
        ‘gulp’ is not recognized as an internal or external command,
        operable program or batch file.

        Also when i Execute my application I get runtime error on console window which says
        1. require is not defined at myprojecturl/node_modules/rxjs/rx.js
        2. require is not defined at myprojecteurl/scripts/app.js

        I have installed npm in my package.json project path.

        Please help.

        Thanks,
        Krupa

        • Also I do have the gulp files like gulp, gulp-clean, gulp-typescript in node_modules folder. The node_modules folder is not included in the project

          • I got it working. The issue was the folder name tsScripts in my project is “TsScripts” So I guess gulpfile.js is case sensitive. On changing the case it worked and the libs folder got created.

            Thanks for the help

      • Hi Mithun,

        Do you have any working sample code for calling a webapi service with parameters using Angular 2 in MVC 5 ?

        I have just started using Angular 2 in MVC 5 and I am not aware about the exact flow of the service call.

        I have created a WebApi project. That has a webmethod which will give me the given user information.

        I want to call this webapi using angular 2.

        What I have achieved so far is:

        1. Created a UserModule.ts which is a class with required user properties like username, email , userpicture etc.
        UserModel.ts

        export class UserModel {
        fullName: string;
        imageUrl: string;
        redirectUrl: string;
        userId: string;
        }

        2. Created a UserInfo.ts which will call the User.Service.ts

        ///
        ///
        ///

        import ‘rxjs/add/operator/switchMap’;
        import { Component, OnInit } from ‘@angular/core’;
        import { ActivatedRoute, Params } from ‘@angular/router’;
        import { Location } from ‘@angular/common’;
        import { UserModel } from ‘./UserModel’;
        import { UserService } from ‘./User.service’;

        // The Office initialize function must be run each time a new page is loaded

        Office.initialize = function () {
        $(document).ready(function () {
        // $(“#toUser”).text(‘Hello world’);
        // displayItemDetails();
        displayToEmailAddress();
        });
        };
        function displayItemDetails() {
        $(“#toUser”).text(‘Hello Krupa’);
        var item = Office.cast.item.toItemRead(Office.context.mailbox.item);
        $(‘#toUser’).text(item.subject);

        }

        function displayToEmailAddress() {

        var toitem = Office.cast.item.toItemRead(Office.context.mailbox.item);

        var itemAdd = new Array();
        itemAdd.push(Office.cast.item.toMessageRead(Office.context.mailbox.item).to);
        itemAdd.push(Office.cast.item.toMessageRead(Office.context.mailbox.item).cc);
        itemAdd.push(Office.cast.item.toMessageRead(Office.context.mailbox.item).from);

        var toAdd = itemAdd[0];
        for (var i = 0; i < toAdd.length; i++) {
        (document.getElementById(“toUser”)).innerHTML += “Display Name: ” + toAdd[i].displayName + “; Email: ” + toAdd[i].emailAddress + “”;
        }

        var cc = itemAdd[1];
        for (var i = 0; i < cc.length; i++) {
        (document.getElementById(“toUser”)).innerHTML += “Display Name: ” + cc[i].displayName + “; Email: ” + cc[i].emailAddress + “”;
        }

        var Bcc = itemAdd[2];
        for (var i = 0; i < cc.length; i++) {
        (document.getElementById(“toUser”)).innerHTML += “Display Name: ” + Bcc.displayName + “; Email: ” + Bcc.emailAddress + “”;
        }

        }

        export class UserInfoComponent implements OnInit {
        UserModel: UserModel;

        constructor(
        private userService: UserService,
        private route: ActivatedRoute,
        private location: Location
        ) { }

        ngOnInit(): void {
        this.route.params
        .switchMap((params: Params) => this.userService.getUser(params[’email’]))
        .subscribe(UserModel => {
        this.UserModel = UserModel
        console.log(this.UserModel);
        }
        );
        }

        }

        3. User.Service.ts will call the webapi method

        User.Service.ts Code

        import { Injectable } from ‘@angular/core’;
        import { Headers, Http } from ‘@angular/http’;

        import ‘rxjs/add/operator/toPromise’;

        import { UserModel } from ‘./UserModel’;

        @Injectable()
        export class UserService {
        private headers = new Headers({ ‘Content-Type’: ‘application/json’ });
        private userUrl = ‘http://localhost:54531/api/User/GetUserData’;

        constructor(private http: Http) {

        }

        getUser(email: string): Promise {
        const url = ‘${this.userUrl}/${email}’;
        return this.http.get(url)
        .toPromise()
        .then(response => response.json().data as UserModel)
        .catch(this.handleError);

        }

        private handleError(error: any): Promise {
        console.error(‘An error occurred’, error); // for demo purposes only
        return Promise.reject(error.message || error);
        }
        }

        In the above getUser method I want to create a usermodel object based upon the data response. But i dont know what should be syntax for it. Can you please guide me ?

        4. User/Index.cshtml – I have a div in this . This div should be loaded with the given user details on my project load.
        So , am i suppose to add userinfo.js reference in my cshtml file or do i need to add userinfo.ts file in the systemjs.config.js file like this

        packages: {
        app: {
        main: ‘./userinfo.js’,
        defaultExtension: ‘js’
        },

        Could you please guide me , how to boot my UserInfo.ts file in my angular application ?

        Any help would be greatly appreciated.

        Thanks,
        Krupa

    • Hi Mithun,

      Do you have any sample application in Angular 2 MVC 5 which calls webapi method with parameter ?

      I have to create one application to show List of users along with the user picture and then the selected user details.

      Any help would be greatly appreciated.

      Thanks,
      Krupa

  21. Is it possible to replace MVC routing with Angular 2 routing completely? I am facing a problem that when refreshing a page it jumps to MVC route which I don’t want to.

      • In my libs folder, I don’t see the jquery & bootstrap folder. Am i doing anything wrong in gulfpile.js ?

        gulp.task(“scriptsNStyles”, function() {
        gulp.src([
        ‘core-js/client/**’,
        ‘systemjs/dist/system.src.js’,
        ‘reflect-metadata/**’,
        ‘rxjs/**’,
        ‘zone.js/dist/**’,
        ‘@angular/**’,
        ‘jquery/dist/jquery.*js’,
        ‘bootstrap/dist/js/bootstrap.*js’
        ], {
        cwd: “node_modules/**”
        })
        .pipe(gulp.dest(“./libs”));
        });

          • The application loads successfully with the desired UI as yours but I still get this error in the console window
            require is not defined in app.ts.

            Also , I am referring to HTTP to call my webapi method but it gives me error like No provider for http

            Do you have any solution for this 2 errors ?

  22. Hi,

    I tried to run this via IIS and got the following error :

    zone.js:1382 XMLHttpRequest cannot load npm:@angular/platform-browser/bundles/platform-browser.umd.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

    Any idea why?
    Many thanks in advance 🙂

  23. Nice tutorial
    Can you please explain how I can connect to oracle database … when I tried to get data..iam getting data but without view..only json result is displayed on screen..

      • I followed tour of heroes tutorial from angular 2 website. And iam calling web api method to retrieve values ..the method is returning values and the values are getting displayed on screen as json string values..

        E.g. [{“id”:1,”name”:”test”}]

        I tried model object and oracle connection string to retrieve values but I was getting error. So I directly connected using oracle connection and iam returning json values in the web api method called from angular 2.

        [HttpGet]
        [Route(“”,name=”api/Home”)]
        Public string Get(){
        Datatable list=new Datatable();
        Db.openconnection();
        String cmd = “select * from autogentrans”;
        Oracledataadapter da = new oracledataadapter(cmd,db.connection);
        da.fill(list);
        String jsonstring =jsonconvert.serializeobject(list);
        return jsonstring;

        }

        Is this correct?

  24. Thanx for the great tutorial. Is anyone elses .html files being cached in the project? I cant seem to update my .html files, and I see all .html files are not migrated to the Scripts folder. I am using .html files as my templates for components. If I cahnge a component everything gets updated fine.

  25. Great setup – It works perfectly locally but I am having some troubles when trying to build the solution on Visual Studio Team Services.:
    C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.targets (2606, 5)
    C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.targets(2606,5): Error : Copying file tsScripts\app.js to obj\Release\Package\PackageTmp\tsScripts\app.js failed. Could not find file ‘tsScripts\app.js’.

  26. We have an existing MVC site and would like to start replacing UI elements with Angular 2 components. Is it possible to load a single component.ts in part of the cshtml page, instead of having to run the entire site as an angular 2 app? I did a proof of concept with Angular 1 and it’s easy to just load the controller.js files inside the cshtml files, but we’d like to know if this same design can be done with angular 2. Thanks.

  27. I found this error after running the default gulp task. Please help
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/common/src/directives/ng_class.d.ts(46,34): error TS2304: Cannot find name ‘Set’.
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/common/src/pipes/async_pipe.d.ts(39,38): error TS2304: Cannot find name ‘Promise’.
    [10:41:43] TypeScript: 70 semantic errors
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/compiler/src/compile_metadata.d.ts(347,20): error TS2304: Cannot find name ‘Set’.
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/compiler/src/compile_metadata.d.ts(348,15): error TS2304: Cannot find name ‘Set’.
    [10:41:43] TypeScript: 70 emit errors
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/compiler/src/directive_normalizer.d.ts(19,100): error TS2304: Cannot find name ‘Promise’.
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/compiler/src/directive_normalizer.d.ts(21,74): error TS2304: Cannot find name ‘Promise’.
    [10:41:43] TypeScript: emit failed
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/compiler/src/offline_compiler.d.ts(15,26): error TS2304: Cannot find name ‘Map’.
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/compiler/src/offline_compiler.d.ts(16,38): error TS2304: Cannot find name ‘Map’.
    [10:41:43] Finished ‘ts’ after 7.33 s
    C:/dev/FirstAssignment/FirstAssignment/FirstAssignment/node_modules/@angular/compiler/src/offline_compiler.d.ts(31,124): error TS2304: Cannot find name ‘Promise’.

  28. How to get ride this error

    Failed to run “C:\Users\user\Downloads\ng2Mvc5Demo-master1\ng2Mvc5Demo-master\ng2Mvc5Demo\Gulpfile.js”…
    cmd.exe /c gulp –tasks-simple
    C:\Users\user\Downloads\ng2Mvc5Demo-master1\ng2Mvc5Demo-master\ng2Mvc5Demo\gulpfile.js:12
    gulp.task(“scriptsNStyles”, () => {
    ^
    SyntaxError: Unexpected token )
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Liftoff.handleArguments (C:\Users\kishor\Downloads\ng2Mvc5Demo-master1\ng2Mvc5Demo-master\ng2Mvc5Demo\node_modules\gulp\bin\gulp.js:116:3)
    at Liftoff. (C:\Users\kishor\Downloads\ng2Mvc5Demo-master1\ng2Mvc5Demo-master\ng2Mvc5Demo\node_modules\gulp\node_modules\liftoff\index.js:198:16)
    at module.exports (C:\Users\kishor\Downloads\ng2Mvc5Demo-master1\ng2Mvc5Demo-master\ng2Mvc5Demo\node_modules\gulp\node_modules\liftoff\node_modules\flagged-respawn\index.js:17:3)
    at Liftoff. (C:\Users\kishor\Downloads\ng2Mvc5Demo-master1\ng2Mvc5Demo-master\ng2Mvc5Demo\node_modules\gulp\node_modules\liftoff\index.js:190:9)

    I have installed nodeJS and TypeScript also and the tsconfig.json is the valid location

    Thanks in advance

  29. You have intermixed TypeScript into your gulpfile.js:

    gulp.task(“scriptsNStyles”, () => {

    should be

    gulp.task(“scriptsNStyles”, function () {

  30. gulp.task(“scriptsNStyles”, () => {
    gulp.src([
    ‘core-js/client/**’,
    ‘systemjs/dist/system.src.js’,
    ‘reflect-metadata/**’,
    ‘rxjs/**’,
    ‘zone.js/dist/**’,
    ‘@angular/**’,
    ‘jquery/dist/jquery.*js’,
    ‘bootstrap/dist/js/bootstrap.*js’
    ], {
    cwd: “node_modules/**”
    })
    .pipe(gulp.dest(“./libs”));
    });

    shows me a error in above code

  31. this is working fine with me as i work with chrome , when working with IE i receive the following errors
    Error: SyntaxError: Expected ‘)’ in regular expression
    Firefox :
    Error: @http://localhost:41935/Scripts/Expenses.component.js:13:27
    @http://localhost:41935/Scripts/Expenses.component.js:1:31
    @http://localhost:41935/Scripts/Expenses.component.js:1:2
    @http://localhost:41935/Scripts/Wallet.component.js:13:28
    @http://localhost:41935/Scripts/Wallet.component.js:1:31
    @http://localhost:41935/Scripts/Wallet.component.js:1:2
    @http://localhost:41935/Scripts/Wallets.component.js:12:26
    @http://localhost:41935/Scripts/Wallets.component.js:1:31
    @http://localhost:41935/Scripts/Wallets.component.js:1:2
    @http://localhost:41935/Scripts/app.js:12:27
    @http://localhost:41935/Scripts/app.js:1:31
    @http://localhost:41935/Scripts/app.js:1:2
    @http://localhost:41935/Scripts/boot.js:4:13
    @http://localhost:41935/Scripts/boot.js:1:31
    @http://localhost:41935/Scripts/boot.js:1:2
    ZoneDelegate.prototype.invoke@http://localhost:41935/libs/zone.js/dist/zone.js:203:19
    Zone.prototype.run@http://localhost:41935/libs/zone.js/dist/zone.js:96:24
    scheduleResolveOrReject/<@http://localhost:41935/libs/zone.js/dist/zone.js:462:52
    ZoneDelegate.prototype.invokeTask@http://localhost:41935/libs/zone.js/dist/zone.js:236:23
    Zone.prototype.runTask@http://localhost:41935/libs/zone.js/dist/zone.js:136:28
    drainMicroTaskQueue@http://localhost:41935/libs/zone.js/dist/zone.js:368:25
    ZoneTask/this.invoke@http://localhost:41935/libs/zone.js/dist/zone.js:308:25

    Evaluating http://localhost:41935/Scripts/Expense.component.js
    Evaluating http://localhost:41935/Scripts/Expenses.component.js
    Evaluating http://localhost:41935/Scripts/Wallet.component.js
    Evaluating http://localhost:41935/Scripts/Wallets.component.js
    Evaluating http://localhost:41935/Scripts/app.js
    Evaluating http://localhost:41935/Scripts/boot.js
    Error loading http://localhost:41935/Scripts/boot.js

  32. As with all your Angular 2 based projects, whether .Net or .Net Core, they build but when I start debugging, they all get stuck at “Loading…”. I’m using the code from your repro verbatim.

    • Press F12 in chrome to see console tab, this will show errors if any while running. Post that error in comments, I will help you to resolve.

      I hope you have TypeScript 2.0 RC installed. That is mandatory

    • OK, sorted it. There are no gulp.js bindings so I suspect that the bindings are not being persisted in your repo’s. Adding an After Build binding to “default” causes the build to hang. Traced this to the “watch” task so removing it from “default” allows the build to complete and when I debug the build now, it works.

  33. Great tutorial! I was able to use this to get started with the official release with few modifications. My only request is that you explain your gulpfile in a bit more detail. I’m new to gulp and struggling to understand most of the code past line 30. Thanks for all you do!

  34. How do I over come the following:

    > cmd.exe /c gulp -b “C:\Users\TMathab\Desktop\ng2Mvc5Demo-Cloned\trunk\ng2Mvc5Demo” –color –gulpfile “C:\Users\TMathab\Desktop\ng2Mvc5Demo-Cloned\trunk\ng2Mvc5Demo\Gulpfile.js” default
    [12:47:51] Using gulpfile ~\Desktop\ng2Mvc5Demo-Cloned\trunk\ng2Mvc5Demo\Gulpfile.js
    [12:47:51] Starting ‘scriptsNStyles’…
    [12:47:51] Finished ‘scriptsNStyles’ after 12 ms
    [12:47:51] Starting ‘ts’…
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/overlay/overlay-directives.d.ts(12,14): error TS1005: ‘=’ expected.
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/overlay/overlay-directives.d.ts(12,24): error TS1005: ‘;’ expected.
    [12:48:05] TypeScript: 11 syntax errors
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/overlay/overlay-directives.d.ts(24,14): error TS1005: ‘=’ expected.
    [12:48:05] TypeScript: emit failed
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/overlay/overlay-directives.d.ts(24,24): error TS1005: ‘;’ expected.
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/overlay/position/connected-position-strategy.d.ts(24,14): error TS1005: ‘=’ expected.
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/overlay/position/connected-position-strategy.d.ts(24,23): error TS1005: ‘;’ expected.
    [12:48:05] Finished ‘ts’ after 14 s
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/overlay/position/connected-position-strategy.d.ts(24,47): error TS1005: ‘=’ expected.
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/portal/portal.d.ts(14,14): error TS1005: ‘=’ expected.
    [12:48:05] Starting ‘watch.ts’…
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/portal/portal.d.ts(14,24): error TS1005: ‘;’ expected.
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/portal/portal.d.ts(53,14): error TS1005: ‘=’ expected.
    [12:48:05] Finished ‘watch.ts’ after 9.96 ms
    C:/Users/TMathab/Desktop/ng2Mvc5Demo-Cloned/trunk/ng2Mvc5Demo/node_modules/@angular2-material/core/portal/portal.d.ts(53,20): error TS1005: ‘;’ expected.
    [12:48:05] Starting ‘watch’…
    [12:48:05] Finished ‘watch’ after 7.25 μs
    [12:48:05] Starting ‘default’…
    [12:48:05] Finished ‘default’ after 5.12 μs